#region Using

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using Gizmox.WebGUI.Common;
using Gizmox.WebGUI.Forms;
using TVC.Layout;
using BUS;
using System.Collections;
using Gizmox.WebGUI.Common.Resources;
using QueryBuilder;
using TVC.Report;
using FlexCel.Core;
using TVC.Modules.Rep;
using System.Globalization;
using System.IO;
using System.Linq;


#endregion

namespace TVC.Modules.Act
{
    public partial class MMEN : ModuleParent, IHostedApplication
    {
        SQLBuilder _sql = new SQLBuilder(processingMode.Details);
        private string _Connecstr;
        private string _DB;
        private DTO.PODInfo PODInfo;
        private string _Prefix;
        private string _Mark;
        private string _processStatusLocal = "";
        BUS.RuleProfileControl RuleProCtr;
        public MMEN()
        {
            InitializeComponent();
            //ItemCode.SetDropDownWith(500);
            _strType = "MME";
            PODInfo = (DTO.PODInfo)Session["USER"];
            _dgvList = dgvList;
            _dgvFilter = gridFilter1;
            if (PODInfo.Business_ID == "HV")
            {
                _Connecstr = MainForm.HVConnect;
                _DB = "HV";
            }
            else
            {
                _Connecstr = MainForm.HLConnect;
                _DB = "HL";
            }
            Doclink.loadUrl();
        }
        public void SetObject(object obj)
        {
        }
        public void InitializeApplication()
        {

            //Doclink.Initialization(GetMainForm().PODInfo.Business_ID, _strType, "", GetMainForm());
            //MainForm = GetMainForm();
            //Doclink.loadUrl();
            ////Doclink.Initialization(_DB, _strType, "MME", MainForm);
            Doclink.Initialization(GetMainForm().PODInfo.Business_ID.ToString().Trim(), "TVC_MFMOV", "", GetMainForm());
        }
        int idAllowEditLanguage = 1;
        int idAddNew = 68;
        int idEdit = 69;
        int idDelete = 70;
        int idDeleteRef = 71;
        int idHold = 72;
        int idPost = 73;
        int idVerified = 232;
        int idPrint = 74;
        int idVision = 75;
        int idRecordCard = 76;
        int idExtractRef = 77;
        int idTransferIn = 78;
        int idTransferOut = 79;
        int idAllocation = 237;
        int idToExcel = 256;
        int idUpdateDL = 277;
        private string _status;
        private string _Reference;
        private string strCode = "";
        private GridLayout layout;
        private string strErr;
        private DataTable dtItemAve;
        private DataTable dtSumQty;
        private DataTable dtHeld;
        private DataTable dtPosted;
        //private string _strPostcode;
        private DTO.TVC_MFMOVInfo _info;
        private string _save;
        private string _MovenmentAccount;
        // private string _PostCode;
        private int _sErrValid_Rul;
        private string _Category;
        private decimal _SumAmount;
        private bool _isvaluechange = true;
        private bool _btnPost = false;
        private string _strFilter;
        private string _strcboHeld = "";
        private string _strcboPosted = "";
        private string _strcboVerify = "";
        private string _gridFilter;
        private bool _reload = false;
        public HostedToolBarElement[] GetToolBarElements()
        {
            ArrayList objElements = new ArrayList();
            if (IsPermis(idAddNew)) objElements.Add(new HostedToolBarButton("Add New", "New", new IconResourceHandle("Add.png"), "C"));
            if (IsPermis(idEdit)) objElements.Add(new HostedToolBarButton("Edit", "Edit", new IconResourceHandle("Edit.png"), "A", false));
            if (IsPermis(idAddNew)) objElements.Add(new HostedToolBarButton("Copy", "Copy", new IconResourceHandle("Copy.png"), "O", false));
            if (IsPermis(idHold) && IsPermis(idEdit) && IsPermis(idAddNew)) objElements.Add(new HostedToolBarButton("Hold", "Hold", new IconResourceHandle("Save.png"), "S", false));
            if (IsPermis(idVerified) && IsPermis(idEdit)) objElements.Add(new HostedToolBarButton("Verify", "Verify", new IconResourceHandle("Verified.jpg"), "Ver", false));
            if (IsPermis(idPost) && IsPermis(idEdit)) objElements.Add(new HostedToolBarButton("Post", "Post", new IconResourceHandle("Approve_icon.png"), "Po", false));
            if (IsPermis(idUpdateDL) && IsPermis(idEdit)) objElements.Add(new HostedToolBarButton("Update Document Link", "Update DL", new IconResourceHandle("Approve_icon.png"), "UDL", false));
            objElements.Add(new HostedToolBarButton("Skip", "Skip", new IconResourceHandle("Reject.png"), "K", false));
            if (IsPermis(idDelete)) objElements.Add(new HostedToolBarButton("Delete ", "Delete ", new IconResourceHandle("RemoveItem.gif"), "X", false));
            if (IsPermis(idDeleteRef)) objElements.Add(new HostedToolBarButton("Delete Ref.", "Delete Ref.", new IconResourceHandle("Delete.png"), "XA", false));
            if (IsPermis(idPrint)) objElements.Add(new HostedToolBarButton("Print", "Print", new IconResourceHandle("Print.png"), "P"));
            if (IsPermis(idVision)) objElements.Add(new HostedToolBarButton("To Vision", "To Vision", new IconResourceHandle("Vision.jpg"), "V", false));
            if (IsPermis(idRecordCard)) objElements.Add(new HostedToolBarButton("View Record Card", "View Record Card", new IconResourceHandle("BusinessCard.png"), "B", false));
            if (IsPermis(idExtractRef)) objElements.Add(new HostedToolBarButton("Extract Ref.", "Extract Ref.", new IconResourceHandle("Down.png"), "D", false));
            if (IsPermis(idAllocation)) objElements.Add(new HostedToolBarButton("Movement Allocation", "Movement Allocation", new IconResourceHandle("Verified.jpg"), "MA"));
            //objElements.Add(new HostedToolBarSeperator());
            //objElements.Add(new HostedToolBarButton("Average Report", "Average Report", new IconResourceHandle("DayView.gif"), "Average"));
            //objElements.Add(new HostedToolBarButton("Min-Max Report", "Min-Max Report", new IconResourceHandle("focus.gif"), "MinMax"));
            //objElements.Add(new HostedToolBarSeperator());
            //objElements.Add(new HostedToolBarButton("Average Email", "Average Email", new IconResourceHandle("ClosedMail.png"), "EAverage"));
            //objElements.Add(new HostedToolBarButton("Min-Max Email", "Min-Max Email", new IconResourceHandle("ClosedMail.png"), "EMinMax")); objElements.Add(new HostedToolBarSeperator());
            //objElements.Add(new HostedToolBarSeperator());
            //if (IsPermis(idTransferIn))
            //    objElements.Add(new HostedToolBarButton("Transfer In", "Import", new IconResourceHandle("Down.png"), "TI"));
            //if (IsPermis(idTransferOut))
            //    objElements.Add(new HostedToolBarButton("Transfer Out", "Export", new IconResourceHandle("Up.png"), "TO"));
            if (IsPermis(idToExcel))
                objElements.Add(new HostedToolBarButton("To Excel", "To Excel", new IconResourceHandle("Up.png"), "TX"));
            objElements.Add(new HostedToolBarButton("Refresh", "Refresh", new IconResourceHandle("Refresh.png"), "R"));

            return (HostedToolBarElement[])objElements.ToArray(typeof(HostedToolBarElement));

        }
        public void OnToolBarButtonClick(HostedToolBarButton objButton, EventArgs objEvent)
        {
            //_Post = false;
            //_PostCode = "Z";

            Cancel = false;
            try
            {
                sErr = "";
                string strAction = (string)objButton.Tag;
                BUS.TVC_MFMOVControl ctr = new BUS.TVC_MFMOVControl(PODInfo.Business_ID);
                _processStatusLocal = "";
                switch (strAction)
                {
                    case "K":
                        skip();
                        break;
                    case "C":
                        _processStatusLocal = "C";
                        // _PostCode = "Z";
                        _Verified = "";
                        AddNew(MovementType);
                        break;
                    case "A":
                        _processStatusLocal = "A";
                        editRecord(MovementType);
                        dtpShipmentDate.Focus();
                        MovementType.Enabled = true;
                        /// Enabled = false mot so field doi vooi movement da post || chuuyen tu PO qua
                        if (_infoDetail.PostCode != "Z" || (_infoDetail.ANAL_M0 == "Y" && _infoDetail.PostCode == "Z"))
                        {
                            MovementType.Enabled = false;
                            MovementType.BackColor = System.Drawing.Color.SkyBlue;
                            dtpMovementDate.Enabled = false;
                            dtpMovementDate.BackColor = System.Drawing.Color.SkyBlue;
                            txtReference.Enabled = false;
                            txtReference.BackColor = System.Drawing.Color.SkyBlue;
                            ItemCode.Enabled = false;
                            cboLocation.Enabled = false;
                            numQuantity.Enabled = false;
                            numAmount.Enabled = false;
                        }
                        if (_Mark == "-")
                            numAmount.Enabled = false;
                        break;
                    case "Ver":
                        Verified();
                        break;
                    case "S":
                        _processStatusLocal = "S";
                        //_Post = false;
                        //lblQty.Focus();
                        saveRecord(MovementType);
                        break;
                    case "Po":
                        //_Post = true;
                        //lblQty.Focus();
                        post(MovementType);
                        break;
                    case "UDL":
                        UpdateDocumentLink();
                        break;
                    case "O":
                        _processStatusLocal = "O";
                        copy(MovementType);
                        strCode = "";
                        if (_infoDetail.PostCode != "Z")
                        {
                            dtpMovementDate.Value = DateTime.Now;
                            // _PostCode = "Z";
                            _Verified = "";
                            txtReference.Text = GetRef(_Prefix);
                        }

                        if (_Mark == "-")
                            numAmount.Enabled = false;
                        lblHoldStatus.Text = "";
                        _CreatedBy = GetMainForm().PODInfo.USER_ID;
                        break;
                    case "X":
                        delete(MovementType);
                        break;
                    case "MA":
                        OpenMMAT();
                        break;
                    case "XA":
                        DeleteRef();
                        break;
                    case "Average":
                        {

                            _sql = SQLBuilder.LoadSQLBuilderFromDataBase("ItemAver1E1_" + PODInfo.Business_ID, "TVC", "");

                            //_sql.Filters[0].ValueFrom = "ZZZ";
                            //_sql.Filters[0].FilterFrom = "ZZZ";
                            //_sql.Filters[0].ValueTo = "";

                            ReportGenerator.User2007 = false;
                            ReportGenerator _report = new ReportGenerator(_sql, "ItemAver1E1_" + PODInfo.Business_ID, "", MainForm.AppConnectString, MainForm.ServerPath + "ReportTemplate\\", MainForm.ServerPath + "Report\\", "");
                            _report.UserID = GetMainForm().PODInfo.USER_ID;
                            ExcelFile exfile = _report.CreateReport();
                            ExcelFile file = exfile;
                            MemoryStream ms = new MemoryStream();
                            file.Save(ms);
                            FileDownloadGateway myDownload = new FileDownloadGateway() { Filename = "Average Alert_" + PODInfo.Business_ID + ".xls" };
                            myDownload.Width = 500;
                            myDownload.SetContentType(FileDownloadGateway.DownloadContentType.MicrosoftExcel);
                            myDownload.StartBytesDownload(this, ms.ToArray());

                        }
                        break;

                    case "MinMax":
                        {

                            _sql = SQLBuilder.LoadSQLBuilderFromDataBase("POMinMax1E1_" + PODInfo.Business_ID, "TVC", "");

                            //_sql.Filters[0].ValueFrom = "ZZZ";
                            //_sql.Filters[0].FilterFrom = "ZZZ";
                            //_sql.Filters[0].ValueTo = "";

                            ReportGenerator.User2007 = false;
                            ReportGenerator _report = new ReportGenerator(_sql, "POMinMax1E1_" + PODInfo.Business_ID, "", MainForm.AppConnectString, MainForm.ServerPath + "ReportTemplate\\", MainForm.ServerPath + "Report\\", "");
                            _report.UserID = GetMainForm().PODInfo.USER_ID;
                            ExcelFile exfile = _report.CreateReport();
                            ExcelFile file = exfile;
                            MemoryStream ms = new MemoryStream();

                            file.Save(ms);
                            FileDownloadGateway myDownload = new FileDownloadGateway() { Filename = "Min-Max Alert_" + PODInfo.Business_ID + ".xls" };

                            myDownload.SetContentType(FileDownloadGateway.DownloadContentType.MicrosoftExcel);
                            myDownload.StartBytesDownload(this, ms.ToArray());

                        }
                        break;
                    // To Vision
                    case "EAverage":
                        SendMail("tavico://TASK?id=ItemAver1E_" + PODInfo.Business_ID);
                        break;
                    case "EMinMax":
                        SendMail("tavico://TASK?id=MinMax1E_" + PODInfo.Business_ID);
                        break;
                    case "V":
                        {

                            BUS.TVC_MVPControl ctrMvp = new TVC_MVPControl(PODInfo.Business_ID);
                            DTO.TVC_MVPInfo infomvp = new DTO.TVC_MVPInfo();
                            infomvp = ctrMvp.Get(MovementType.Value.ToString(), ref sErr);
                            _sql = SQLBuilder.LoadSQLBuilderFromDataBase(infomvp.Template, "TVC", "");
                            if (_Reference != "")
                            {
                                _sql.Filters[0].ValueFrom = _Reference;
                                _sql.Filters[0].ValueTo = "";
                                _sql.Filters[0].FilterFrom = _Reference;
                            }
                            else
                            {
                                _sql.Filters[0].ValueFrom = "ZZZ";
                                _sql.Filters[0].ValueTo = "";
                                _sql.Filters[0].FilterFrom = "ZZZ";
                            }
                            ReportGenerator _report = new ReportGenerator(_sql, infomvp.Template, "", MainForm.AppConnectString, MainForm.ServerPath + "ReportTemplate\\", MainForm.ServerPath + "Report\\", "");
                            ReportGenerator.User2007 = false;
                            _report.UserID = GetMainForm().PODInfo.USER_ID;
                            ExcelFile exfile = _report.CreateReport();
                            ExcelFile file = exfile;
                            MemoryStream ms = new MemoryStream();
                            file.Save(ms);
                            FileDownloadGateway myDownload = new FileDownloadGateway() { Filename = _report.QdCode + "_" + _Reference + ".xls" };

                            myDownload.SetContentType(FileDownloadGateway.DownloadContentType.MicrosoftExcel);
                            myDownload.StartBytesDownload(this, ms.ToArray());

                        }
                        break;

                    case "B":
                        {
                            _sql = SQLBuilder.LoadSQLBuilderFromDataBase("SRC01_" + PODInfo.Business_ID, "TVC", "");
                            if (ItemCode.Value.ToString() == "")
                            {
                                _sql.Filters[0].FilterFrom = "ZZZ";
                                _sql.Filters[0].ValueFrom = "ZZZ";
                                _sql.Filters[0].ValueTo = "";
                            }
                            else
                            {

                                _sql.Filters[0].FilterFrom = ItemCode.Value.ToString();
                                _sql.Filters[0].ValueFrom = ItemCode.Value.ToString();
                                _sql.Filters[0].ValueTo = "";
                            }
                            ReportGenerator _report = new ReportGenerator(_sql, "SRC01_" + PODInfo.Business_ID, "", MainForm.AppConnectString, MainForm.ServerPath + "ReportTemplate\\", MainForm.ServerPath + "Report\\", "");
                            ReportGenerator.User2007 = false;
                            _report.UserID = GetMainForm().PODInfo.USER_ID;
                            ExcelFile exfile = _report.CreateReport();
                            frmViewReport frmVi = new frmViewReport(_report.QdCode, GetMainForm());
                            frmVi.filename = _report.QdCode;
                            frmVi.Xls = exfile;
                            frmVi.BringToFront();
                            frmVi.Show();

                        }
                        break;

                    case "D":
                        {
                            _sql = SQLBuilder.LoadSQLBuilderFromDataBase("ExtractRef01_" + PODInfo.Business_ID, "TVC", "");
                            if (_Reference != "")
                            {
                                _sql.Filters[0].ValueFrom = _Reference;
                                _sql.Filters[0].FilterFrom = _Reference;
                                _sql.Filters[0].ValueTo = "";
                            }
                            else
                            {
                                _sql.Filters[0].ValueFrom = "ZZZ";
                                _sql.Filters[0].FilterFrom = "ZZZ";
                                _sql.Filters[0].ValueTo = "";
                            }
                            ReportGenerator.User2007 = false;
                            ReportGenerator _report = new ReportGenerator(_sql, "ExtractRef01_" + PODInfo.Business_ID, "", MainForm.AppConnectString, MainForm.ServerPath + "ReportTemplate\\", MainForm.ServerPath + "Report\\", "");
                            _report.UserID = GetMainForm().PODInfo.USER_ID;
                            ExcelFile exfile = _report.CreateReport();
                            ExcelFile file = exfile;
                            MemoryStream ms = new MemoryStream();

                            file.Save(ms);
                            FileDownloadGateway myDownload = new FileDownloadGateway() { Filename = _report.QdCode + "_" + _Reference + ".xls" };

                            myDownload.SetContentType(FileDownloadGateway.DownloadContentType.MicrosoftExcel);
                            myDownload.StartBytesDownload(this, ms.ToArray());
                        }
                        break;

                    case "R":
                        refresh();
                        break;
                    case "TI":
                        Forms.frmTransferIn frmTI = new Forms.frmTransferIn(_strType, GetMainForm());
                        frmTI.ShowDialog();
                        break;
                    case "TO":
                        export2Xml();
                        break;
                    case "TX":
                        export2Excel();
                        break;
                    case "P":
                        {
                            if (_Reference != "" && _Reference != null)
                            {
                                _sql = SQLBuilder.LoadSQLBuilderFromDataBase("RefPrint01_" + PODInfo.Business_ID, "TVC", "");
                                _sql.Filters[0].ValueFrom = _Reference;
                                _sql.Filters[0].FilterFrom = _Reference;
                                _sql.Filters[0].ValueTo = "";
                                ReportGenerator.User2007 = false;
                                ReportGenerator _report = new ReportGenerator(_sql, "RefPrint01_" + PODInfo.Business_ID, "", MainForm.AppConnectString, MainForm.ServerPath + "ReportTemplate\\", MainForm.ServerPath + "Report\\", "");
                                _report.UserID = GetMainForm().PODInfo.USER_ID;
                                ExcelFile exfile = _report.CreateReport();
                                ExcelFile file = exfile;
                                MemoryStream ms = new MemoryStream();
                                file.Save(ms);
                                FileDownloadGateway myDownload = new FileDownloadGateway() { Filename = _report.QdCode + "_" + _Reference + ".xls" };
                                myDownload.SetContentType(FileDownloadGateway.DownloadContentType.MicrosoftExcel);
                                myDownload.StartBytesDownload(this, ms.ToArray());
                            }
                        }
                        break;
                }
                if (Cancel == false)
                {
                    //SetupToolBar(strAction);
                    //_processStatus = strAction;
                    //_processStatusLocal = strAction;
                }
                if (sErr == "")
                    ThrowMsg("Command: " + _processStatus);
            }
            catch (Exception ex)
            {
                ThrowMsg(ex.Message + Environment.NewLine + ex.Source);
            }
        }

        private void UpdateDocumentLink()
        {
            BUS.TVC_MFMOVControl ctr = new BUS.TVC_MFMOVControl(PODInfo.Business_ID);
            DTO.TVC_MFMOVInfo info = GetData();
            object trans = ctr.BeginTransaction(ref sErr);
            Doclink._trans = trans;
            Doclink.Copy(info.Reference);
            Doclink.Update(info.Reference);
            if (sErr == "")
            {
                ctr.CommitTransaction(ref sErr);
                enableForm(false);
                skip();
            }
            else
                MessageBox.Show(sErr, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, false);
        }


        private void post(CustomControl.LookupBox MovementType)
        {
            string sWrn = "";
            //_Post = true;
            if (_Verified != "Y")
            {
                MessageBox.Show("This reference had not been verified!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, false);
                return;
            }
            ErrorStatus err = validateForm(ref sErr);

            if (err == ErrorStatus.ERROR)
            {
                MessageBox.Show(sErr, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, false);
                return;
            }
            if (err == ErrorStatus.WARNING)
            {
                sWrn = sErr;
                sErr = "";
            }
            // STEP 2 : UPDATE current record and update reference
            BUS.TVC_MFMOVControl ctr = new BUS.TVC_MFMOVControl(PODInfo.Business_ID);
            DTO.TVC_MFMOVInfo info = GetData();
            info.PostCode = _infoDetail.PostCode;
            info.PostDate = _infoDetail.PostDate;
            info.PostBy = _infoDetail.PostBy;
            info.ANAL_M0 = _infoDetail.ANAL_M0;
            info.ANAL_M1 = _infoDetail.ANAL_M1;
            info.ANAL_M2 = _infoDetail.ANAL_M2;
            info.ANAL_M3 = _infoDetail.ANAL_M3;
            info.ANAL_M4 = _infoDetail.ANAL_M4;
            info.Hold = _infoDetail.Hold;
            object trans = ctr.BeginTransaction(ref sErr);

            info.SUNStatus = "N";

            info.ModifiedBy = PODInfo.USER_ID;
            info.ModifiedDate = DateTime.Now;
            Doclink._trans = trans;

            if (sErr == "") Doclink.Update(info.Reference);
            if (sErr == "") sErr = ctr.Update(info);
            if (sErr == "") sErr = ctr.UpdateRef(info);

            // STEP 3: Validate Reference
            bool isPost = true;
            if (sErr == "")
            {
                dtItemAve = ctr.GetbyReference(txtReference.Text, null, ref sErr);
                if (dtItemAve.Select("Verified <> 'Y'").Length > 0)
                {
                    sErr = "This reference had not been verified!";
                }

                if (dtItemAve.Select("PostCode <> 'Z'").Length > 0)
                {
                    isPost = false;
                }

                if (sErr == "")
                {
                    int _sErrValid_Rul = RuleProCtr.Valid_Rule("TVC_MFMOV", dtItemAve, ref sErr);
                    if (_sErrValid_Rul == 1)
                    {
                        if (sErr == "") sErr = "ERROR";
                    }
                    else if (sErr != "")
                    {
                        sWrn += sErr;
                        sErr = "";
                    }
                }
            }

            if (sErr == "" && sWrn == "")
            {
                DataTable dtSumQty = ctr.GetItemSumByRef(txtReference.Text, ref sErr);
                if (sErr == "" && isPost) sErr = PostStep2(ctr, ref info, dtItemAve, dtSumQty);

                finishPost(ctr, info, sErr);
            }
            else if (sErr == "")
            {
                MessageBox.Show(sWrn += "\nWould you like to post this REFERENCE?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question, delegate(object newSender, EventArgs newArgs)
                {
                    if (((MessageBoxWindow)newSender).DialogResult == DialogResult.Yes)
                    {
                        DataTable dtSumQty = ctr.GetItemSumByRef(txtReference.Text, ref sErr);
                        if (sErr == "" && isPost) sErr = PostStep2(ctr, ref info, dtItemAve, dtSumQty);
                        finishPost(ctr, info, sErr);
                    }
                    else
                    {
                        ctr.RollbackTransaction(ref sErr);
                    }
                }, false);
            }
            else finishPost(ctr, info, sErr);

        }

        private void finishPost(BUS.TVC_MFMOVControl ctr, DTO.TVC_MFMOVInfo info, string sErr)
        {
            if (sErr == "")
            {
                _infoDetail.PostCode = info.PostCode;
                _infoDetail.PostDate = info.PostDate;
                _infoDetail.PostBy = info.PostBy;
                _infoDetail.Hold = info.Hold;
                _Verified = info.Verified;

                ctr.CommitTransaction(ref sErr);

            }
            else
            {
                _infoDetail.PostCode = "Z";
                ctr.RollbackTransaction(ref sErr);
            }

            if (sErr != "")
            {
                MessageBox.Show(sErr, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, false);
            }
            else
            {
                lblHoldStatus.Text = "POSTED " + info.PostCode;
                //MessageBox.Show("This reference is posted successfully", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information, false);
                reloadList();
                afterUpdate();
                enableForm(false);
                _processStatus = "V";
                SetupToolBar(_processStatus);
            }
        }

        /*
        private string postConfirmed(ref bool isConfirm)
        {
            sErr = "";
            BUS.TVC_MFMOVControl ctr = new BUS.TVC_MFMOVControl(PODInfo.Business_ID);
            DTO.TVC_MFMOVInfo info = GetData();
            object trans = ctr.BeginTransaction(ref sErr);
            if (_PostCode == null || _PostCode == "Z")
            {
                info.PostCode = "Z";
                if (info.Hold == "")
                    info.Hold = "Y";
                info.SUNStatus = "N";
            }
            else
            {
                //info.PostCode = _PostCode;
                //info.Hold = "";
                info.SUNStatus = "N";
            }
            info.ModifiedBy = PODInfo.USER_ID;
            info.ModifiedDate = DateTime.Now;
            Doclink._trans = trans;
            //if (_Post == true && info.Verified != "Y")
            //{
            //    sErr = txtReference.Text.Trim() + " has not been verified! ";
            //}
            if (sErr == "") Doclink.Update(info.Reference);
            if (sErr == "") sErr = ctr.Update(info);
            if (sErr == "") sErr = ctr.UpdateRef(info);

            if (sErr == "") ctr.CommitTransaction(ref sErr);
            else ctr.RollbackTransaction(ref sErr);

            if (_Post == true && info.PostCode == "Z" && sErr == "")
            {
                sErr = Post(ctr, info.Reference, info, ref isConfirm);
            }
            if (!isConfirm) BalRef(info.Reference);
            return sErr;
        }

        */
        private void SendMail(string kq)
        {
            string[] cmd = kq.Split('?');
            CmdManager.UserID = GetMainForm().PODInfo.USER_ID;
            CmdManager.Db = GetMainForm().DB;
            CmdManager.TempPath = MainForm.ServerPath + "ReportTemplate\\";
            CmdManager.ReptPath = MainForm.ServerPath + "Report\\";
            //CmdManager.AppConnect = MainForm.AppConnectString;
            CmdManager.DocumentDirectory = MainForm.ServerPath + "local_log/";
            // CmdManager.RepConnect
            string value = CmdManager.RunCmd(cmd[0], cmd[1]);
            //, (obj, etv) =>
            //{
            //    AsyncCompletedEventArgs tmp = etv as AsyncCompletedEventArgs;
            //    if (tmp != null)
            //    {
            //        if (tmp.Error != null)
            //        {
            //            Forms.frmMsg msg = new Forms.frmMsg();
            //            msg.Text = "Error";
            //            msg.ShowMsg("ERROR: " + tmp.Error.Message);
            //        }
            //        else
            //        {
            //            Forms.frmMsg msg = new Forms.frmMsg();
            //            msg.Text = "Success";
            //            msg.ShowMsg("Send mail Successful!");
            //        }


            //    }
            //});


            if (value != "") MessageBox.Show(value, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, false);
            else MessageBox.Show("Send mail Successful!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information, false);
        }
        protected override void FireEvent(Gizmox.WebGUI.Common.Interfaces.IEvent objEvent)
        {
            if (objEvent.Type == "MyShowMessage")
            {
                MessageBox.Show("Now I can continue processing", false);
            }
            else
            {
                base.FireEvent(objEvent);
            }
        }
        private void OpenMMAT()
        {
            GetMainForm().SelectCategory("MMA", "");
        }

        private void Verified()
        {
            string sWrn = "";
            ErrorStatus err = validateForm(ref sErr);

            if (err == ErrorStatus.ERROR)
            {
                MessageBox.Show(sErr, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, false);
                return;
            }
            if (err == ErrorStatus.WARNING)
            {
                sWrn = sErr;
                sErr = "";
            }
            BUS.TVC_MFMOVControl ctr = new BUS.TVC_MFMOVControl(GetMainForm().PODInfo.Business_ID);

            DataTable dtItemAve = ctr.GetbyReference(txtReference.Text, null, ref sErr);

            if (sErr == "")
            {
                int _sErrValid_Rul = RuleProCtr.Valid_Rule("TVC_MFMOV", dtItemAve, ref sErr);
                if (_sErrValid_Rul == 1)
                {
                    if (sErr == "") sErr = "ERROR";
                }
                else if (sErr != "")
                {
                    sWrn += sErr;
                    sErr = "";
                }
            }

            if (sErr != "")
            {
                MessageBox.Show(sErr, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, false);
                return;
            }

            if (sWrn != "") sWrn += "\n";
            //MessageBox.Show(sWrn + " Would you like to verify Reference " + txtReference.Text.Trim() + " ?", "Delete", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, delegate(object newSender, EventArgs newArgs)
            //{
            //    if (((MessageBoxWindow)newSender).DialogResult == DialogResult.OK)
            //    {
            sErr = ctr.UpdateVerified(txtReference.Text.Trim(), "Y");
            if (sErr == "")
            {
                enableForm(false);
                _infoDetail.Verified = "Y";
                _Verified = "Y";
                reloadList();
                LoadHeldCombo();
                LoadVerifyCombo();
                _processStatus = "V";
                SetupToolBar("V");
            }
            //    }
            //}, false);
        }
        public override void refresh()
        {
            _reload = true;
            _strFilter = _gridFilter;
            UpdateSunStatus();
            reloadList();
            DTO.TVC_MFMOVInfo info = GetData();
            _isvaluechange = false;
            _Verified = "";
            _CreatedBy = GetMainForm().PODInfo.USER_ID;

            LoadCombo();

            SetData(info);
            //_processStatusLocal = strAction;
            //BUS.TVC_LOOKUPControl lookup = new BUS.TVC_LOOKUPControl(PODInfo.Business_ID);
            //string tableTVC_MFMOV = "TVC_MFMOVPRV";
            //if (PODInfo.Business_ID == "HV")
            //{
            //    tableTVC_MFMOV = "TVC_MFMOVHVJ";
            //}
            //dtHeld = lookup.GetQuery("SELECT Reference FROM " + tableTVC_MFMOV + " WHERE (((Hold)='Y')) GROUP BY Reference ORDER BY Reference", ref sErr);
            //DataRow dr2 = dtHeld.NewRow();
            //dtHeld.Rows.Add(dr2);
            //DataView dv = dtHeld.DefaultView;
            //dv.Sort = "Reference ASC";
            //cboHeld.DataSource = dv.ToTable();
            ////cboHeld.SelectedValue = _strcboHeld;
            //dtPosted = lookup.GetQuery("SELECT Reference, PostCode,(Reference + ' - ' + PostCode) as DisplayCBO,SUNStatus FROM " + tableTVC_MFMOV + " GROUP BY Reference, PostCode, SUNStatus HAVING (((PostCode)<>'Z') 	AND ((SUNStatus)='N')) ORDER BY PostCode", ref sErr);
            //DataRow dr3 = dtPosted.NewRow();
            //dtPosted.Rows.Add(dr3);
            //DataView dv2 = dtPosted.DefaultView;
            //dv2.Sort = "PostCode ASC";
            //cboPosted.DataSource = dv2.ToTable();
            //cboPosted.SelectedValue = _strcboPosted;
            //enableForm(false);
            //SetupToolBar("V");
            _isvaluechange = true;
            _reload = false;
        }
        Dictionary<string, ToolBarButton> _arrButton = new Dictionary<string, ToolBarButton>();
        protected override void SetupToolBar(string strAction)
        {
            ToolBar tbarLocal = GetTbarLocal();
            bool on = true, off = false;
            if (tbarLocal == null) return;
            if (_arrButton.Count == 0)
            {
                foreach (ToolBarButton button in tbarLocal.Buttons)
                {
                    if (button.Name != "")
                    {
                        _arrButton.Add(button.Name, button);
                    }
                }
            }

            if (_arrButton.Count == 0) return;

            switch (strAction)
            {
                case "C":
                    if (_arrButton.ContainsKey("C")) _arrButton["C"].Enabled = off;
                    if (_arrButton.ContainsKey("A")) _arrButton["A"].Enabled = off;
                    if (_arrButton.ContainsKey("S")) _arrButton["S"].Enabled = on;
                    if (_arrButton.ContainsKey("K")) _arrButton["K"].Enabled = on;
                    if (_arrButton.ContainsKey("Ver")) _arrButton["Ver"].Enabled = off;
                    if (_arrButton.ContainsKey("Po")) _arrButton["Po"].Enabled = off;
                    if (_arrButton.ContainsKey("O")) _arrButton["O"].Enabled = off;
                    if (_arrButton.ContainsKey("X")) _arrButton["X"].Enabled = off;
                    if (_arrButton.ContainsKey("XA")) _arrButton["XA"].Enabled = off;
                    if (_arrButton.ContainsKey("V")) _arrButton["V"].Enabled = on;
                    if (_arrButton.ContainsKey("B")) _arrButton["B"].Enabled = on;
                    if (_arrButton.ContainsKey("D")) _arrButton["D"].Enabled = on;
                    if (_arrButton.ContainsKey("MA")) _arrButton["MA"].Enabled = on;
                    if (_arrButton.ContainsKey("TX")) _arrButton["TX"].Enabled = on;

                    if (_arrButton.ContainsKey("Average")) _arrButton["Average"].Enabled = on;
                    if (_arrButton.ContainsKey("MinMax")) _arrButton["MinMax"].Enabled = on;
                    if (_arrButton.ContainsKey("EAverage")) _arrButton["EAverage"].Enabled = on;
                    if (_arrButton.ContainsKey("EMinMax")) _arrButton["EMinMax"].Enabled = on;

                    break;
                case "A":
                    if (_arrButton.ContainsKey("C")) _arrButton["C"].Enabled = off;
                    if (_arrButton.ContainsKey("A")) _arrButton["A"].Enabled = off;
                    if (_arrButton.ContainsKey("UDL")) _arrButton["UDL"].Enabled = on;
                    if (_infoDetail.PostCode == "Z")
                    {
                        if (_arrButton.ContainsKey("S")) _arrButton["S"].Enabled = on;
                        if (_arrButton.ContainsKey("Ver")) _arrButton["Ver"].Enabled = on;
                    }
                    else
                    {
                        if (_arrButton.ContainsKey("S")) _arrButton["S"].Enabled = off;
                        if (_arrButton.ContainsKey("Ver")) _arrButton["Ver"].Enabled = off;
                    }
                    if (_arrButton.ContainsKey("K")) _arrButton["K"].Enabled = on;
                    if (_Verified == "Y")
                    { if (_arrButton.ContainsKey("Po")) _arrButton["Po"].Enabled = on; }
                    else { if (_arrButton.ContainsKey("Po")) _arrButton["Po"].Enabled = off; }

                    /*
                    if (_infoDetail != null && _infoDetail.PostCode == "Z" && _infoDetail.ANAL_M0 != "Y")
                    {
                        foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "S") { button.Enabled = on; break; } }
                        foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "Ver") { button.Enabled = on; break; } }
                        foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "X") { button.Enabled = on; break; } }
                        foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "XA") { button.Enabled = on; break; } }
                        if (_Verified == "Y") foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "Po") { button.Enabled = on; break; } }
                        else foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "Po") { button.Enabled = off; break; } }
                    }
                    else
                    {
                        if (_infoDetail != null && _infoDetail.PostCode != "Z")
                            foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "Ver") { button.Enabled = off; break; } }
                        else
                            foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "Ver") { button.Enabled = on; break; } }
                        foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "S") { button.Enabled = off; break; } }
                        foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "Po") { button.Enabled = on; break; } }
                        foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "X") { button.Enabled = off; break; } }
                        foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "XA") { button.Enabled = off; break; } }
                    }
                    */
                    if (_arrButton.ContainsKey("O")) _arrButton["O"].Enabled = off;
                    if (_arrButton.ContainsKey("X")) _arrButton["X"].Enabled = off;
                    if (_arrButton.ContainsKey("XA")) _arrButton["XA"].Enabled = off;
                    if (_arrButton.ContainsKey("V")) _arrButton["V"].Enabled = on;
                    if (_arrButton.ContainsKey("B")) _arrButton["B"].Enabled = on;
                    if (_arrButton.ContainsKey("D")) _arrButton["D"].Enabled = on;
                    if (_arrButton.ContainsKey("TX")) _arrButton["TX"].Enabled = on;
                    if (_arrButton.ContainsKey("MA")) _arrButton["MA"].Enabled = on;
                    if (_arrButton.ContainsKey("Average")) _arrButton["Average"].Enabled = on;
                    if (_arrButton.ContainsKey("MinMax")) _arrButton["MinMax"].Enabled = on;
                    if (_arrButton.ContainsKey("EAverage")) _arrButton["EAverage"].Enabled = on;
                    if (_arrButton.ContainsKey("EMinMax")) _arrButton["EMinMax"].Enabled = on;
                    break;
                case "S":
                    if (_arrButton.ContainsKey("C")) _arrButton["C"].Enabled = on;
                    if (_arrButton.ContainsKey("A")) _arrButton["A"].Enabled = on;

                    if (_arrButton.ContainsKey("S")) _arrButton["S"].Enabled = off;
                    if (_arrButton.ContainsKey("Ver")) _arrButton["Ver"].Enabled = off;
                    if (_arrButton.ContainsKey("K")) _arrButton["K"].Enabled = off;
                    if (_arrButton.ContainsKey("Po")) _arrButton["Po"].Enabled = off;
                    if (_arrButton.ContainsKey("UDL")) _arrButton["UDL"].Enabled = off;

                    /*
                    if (_infoDetail != null && _infoDetail.PostCode == "Z" && _infoDetail.ANAL_M0 != "Y")
                    {
                        foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "S") { button.Enabled = on; break; } }
                        foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "Ver") { button.Enabled = on; break; } }
                        foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "X") { button.Enabled = on; break; } }
                        foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "XA") { button.Enabled = on; break; } }
                        if (_Verified == "Y") foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "Po") { button.Enabled = on; break; } }
                        else foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "Po") { button.Enabled = off; break; } }
                    }
                    else
                    {
                        if (_infoDetail != null && _infoDetail.PostCode != "Z")
                            foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "Ver") { button.Enabled = off; break; } }
                        else
                            foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "Ver") { button.Enabled = on; break; } }
                        foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "S") { button.Enabled = off; break; } }
                        foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "Po") { button.Enabled = on; break; } }
                        foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "X") { button.Enabled = off; break; } }
                        foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "XA") { button.Enabled = off; break; } }
                    }
                    */
                    if (_arrButton.ContainsKey("O")) _arrButton["O"].Enabled = on;
                    if (_infoDetail != null && _infoDetail.PostCode == "Z" && _infoDetail.ANAL_M0 != "Y")
                    {
                        if (_arrButton.ContainsKey("X")) _arrButton["X"].Enabled = on;
                        if (_arrButton.ContainsKey("XA")) _arrButton["XA"].Enabled = on;
                    }
                    else
                    {
                        if (_arrButton.ContainsKey("X")) _arrButton["X"].Enabled = off;
                        if (_arrButton.ContainsKey("XA")) _arrButton["XA"].Enabled = off;
                    }

                    if (_arrButton.ContainsKey("V")) _arrButton["V"].Enabled = on;
                    if (_arrButton.ContainsKey("B")) _arrButton["B"].Enabled = on;
                    if (_arrButton.ContainsKey("D")) _arrButton["D"].Enabled = on;
                    if (_arrButton.ContainsKey("MA")) _arrButton["MA"].Enabled = on;
                    if (_arrButton.ContainsKey("TX")) _arrButton["TX"].Enabled = on;
                    if (_arrButton.ContainsKey("Average")) _arrButton["Average"].Enabled = on;
                    if (_arrButton.ContainsKey("MinMax")) _arrButton["MinMax"].Enabled = on;
                    if (_arrButton.ContainsKey("EAverage")) _arrButton["EAverage"].Enabled = on;
                    if (_arrButton.ContainsKey("EMinMax")) _arrButton["EMinMax"].Enabled = on;
                    break;
                case "Ver":                    
                    break;
                case "Po":                    
                    break;
                case "O":
                    if (_arrButton.ContainsKey("C")) _arrButton["C"].Enabled = off;
                    if (_arrButton.ContainsKey("A")) _arrButton["A"].Enabled = off;
                    if (_arrButton.ContainsKey("S")) _arrButton["S"].Enabled = on;
                    if (_arrButton.ContainsKey("K")) _arrButton["K"].Enabled = on;
                    if (_arrButton.ContainsKey("Ver")) _arrButton["Ver"].Enabled = off;
                    if (_arrButton.ContainsKey("Po")) _arrButton["Po"].Enabled = off;
                    if (_arrButton.ContainsKey("O")) _arrButton["O"].Enabled = off;
                    if (_arrButton.ContainsKey("X")) _arrButton["X"].Enabled = off;
                    if (_arrButton.ContainsKey("XA")) _arrButton["XA"].Enabled = off;
                    if (_arrButton.ContainsKey("V")) _arrButton["V"].Enabled = on;
                    if (_arrButton.ContainsKey("B")) _arrButton["B"].Enabled = on;
                    if (_arrButton.ContainsKey("D")) _arrButton["D"].Enabled = on;
                    if (_arrButton.ContainsKey("MA")) _arrButton["MA"].Enabled = on;
                    if (_arrButton.ContainsKey("TX")) _arrButton["TX"].Enabled = on;
                    if (_arrButton.ContainsKey("Average")) _arrButton["Average"].Enabled = on;
                    if (_arrButton.ContainsKey("MinMax")) _arrButton["MinMax"].Enabled = on;
                    if (_arrButton.ContainsKey("EAverage")) _arrButton["EAverage"].Enabled = on;
                    if (_arrButton.ContainsKey("EMinMax")) _arrButton["EMinMax"].Enabled = on;
                    break;
                case "X":
                case "XA":
                case "B":
                case "D":
                case "P":
                    break;
                //case "R":
                //    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "C") { button.Enabled = on; break; } }
                //    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "A") { button.Enabled = on; break; } }
                //    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "S") { button.Enabled = off; break; } }
                //    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "Po") { button.Enabled = off; break; } }
                //    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "O") { button.Enabled = on; break; } }
                //    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "X") { button.Enabled = on; break; } }
                //    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "XA") { button.Enabled = on; break; } }
                //    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "V") { button.Enabled = on; break; } }
                //    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "B") { button.Enabled = on; break; } }
                //    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "D") { button.Enabled = on; break; } }
                //    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "P") { button.Enabled = on; break; } }
                //    break;
                case "V":
                    if (_arrButton.ContainsKey("C")) _arrButton["C"].Enabled = on;
                    if (_arrButton.ContainsKey("A")) _arrButton["A"].Enabled = on;

                    if (_arrButton.ContainsKey("S")) _arrButton["S"].Enabled = off;

                    if (_arrButton.ContainsKey("Ver")) _arrButton["Ver"].Enabled = off;
                    if (_arrButton.ContainsKey("K")) _arrButton["K"].Enabled = off;
                    if (_arrButton.ContainsKey("Po")) _arrButton["Po"].Enabled = off;


                    /*
                    if (_infoDetail != null && _infoDetail.PostCode == "Z" && _infoDetail.ANAL_M0 != "Y")
                    {
                        foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "S") { button.Enabled = on; break; } }
                        foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "Ver") { button.Enabled = on; break; } }
                        foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "X") { button.Enabled = on; break; } }
                        foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "XA") { button.Enabled = on; break; } }
                        if (_Verified == "Y") foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "Po") { button.Enabled = on; break; } }
                        else foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "Po") { button.Enabled = off; break; } }
                    }
                    else
                    {
                        if (_infoDetail != null && _infoDetail.PostCode != "Z")
                            foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "Ver") { button.Enabled = off; break; } }
                        else
                            foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "Ver") { button.Enabled = on; break; } }
                        foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "S") { button.Enabled = off; break; } }
                        foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "Po") { button.Enabled = on; break; } }
                        foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "X") { button.Enabled = off; break; } }
                        foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "XA") { button.Enabled = off; break; } }
                    }
                    */
                    if (_arrButton.ContainsKey("O")) _arrButton["O"].Enabled = on;
                    if (_infoDetail != null && _infoDetail.PostCode == "Z")
                    {
                        if (_infoDetail.ANAL_M0 == "Y")
                        {
                            if (_arrButton.ContainsKey("X")) _arrButton["X"].Enabled = off;
                            if (_arrButton.ContainsKey("XA")) _arrButton["XA"].Enabled = on;
                        }
                        else
                        {
                            if (_arrButton.ContainsKey("X")) _arrButton["X"].Enabled = on;
                            if (_arrButton.ContainsKey("XA")) _arrButton["XA"].Enabled = on;
                        }
                    }
                    else
                    {
                        if (_arrButton.ContainsKey("X")) _arrButton["X"].Enabled = off;
                        if (_arrButton.ContainsKey("XA")) _arrButton["XA"].Enabled = off;
                    }

                    if (_arrButton.ContainsKey("V")) _arrButton["V"].Enabled = on;
                    if (_arrButton.ContainsKey("B")) _arrButton["B"].Enabled = on;
                    if (_arrButton.ContainsKey("D")) _arrButton["D"].Enabled = on;
                    if (_arrButton.ContainsKey("MA")) _arrButton["MA"].Enabled = on;
                    if (_arrButton.ContainsKey("TX")) _arrButton["TX"].Enabled = on;
                    if (_arrButton.ContainsKey("Average")) _arrButton["Average"].Enabled = on;
                    if (_arrButton.ContainsKey("MinMax")) _arrButton["MinMax"].Enabled = on;
                    if (_arrButton.ContainsKey("EAverage")) _arrButton["EAverage"].Enabled = on;
                    if (_arrButton.ContainsKey("EMinMax")) _arrButton["EMinMax"].Enabled = on;

                    break;
            }

        }

        protected override void afterUpdate()
        {
            _isvaluechange = false;
            LoadPostCombo();
            LoadHeldCombo();
            LoadVerifyCombo();
            _isvaluechange = true;
        }

        private void LoadHeldCombo()
        {
            _isvaluechange = false;
            BUS.TVC_MFMOVControl ctr = new TVC_MFMOVControl(PODInfo.Business_ID);
            dtHeld = ctr.GetHeld("Y", ref sErr);
            //dtHeld = lookup.GetQuery("SELECT Reference FROM " + tableTVC_MFMOV + " WHERE (((Hold)='Y')) GROUP BY Reference ORDER BY Reference", ref sErr);
            DataRow dr5 = dtHeld.NewRow();
            dtHeld.Rows.Add(dr5);
            DataView dv1 = dtHeld.DefaultView;
            dv1.Sort = "Reference ASC";
            cboHeld.DataSource = dv1.ToTable();
            cboHeld.DisplayMember = "Reference";
            cboHeld.ValueMember = "Reference";
            cboHeld.SelectedValue = _strcboHeld;
            _isvaluechange = true;
        }

        private void LoadPostCombo()
        {
            _isvaluechange = false;
            BUS.TVC_MFMOVControl ctr = new TVC_MFMOVControl(PODInfo.Business_ID);
            dtPosted = ctr.GetPost(ref sErr);
            DataRow dr4 = dtPosted.NewRow();
            dr4["Reference"] = "";
            dr4["PostCode"] = "";
            dr4["DisplayCBO"] = "";
            dtPosted.Rows.Add(dr4);
            DataView dv4 = dtPosted.DefaultView;
            dv4.Sort = "PostCode ASC";
            cboPosted.DataSource = dv4.ToTable();
            cboPosted.DisplayMember = "DisplayCBO";
            cboPosted.ValueMember = "Reference";
            cboPosted.SelectedValue = _strcboPosted;
            _isvaluechange = true;
        }

        private void LoadVerifyCombo()
        {
            _isvaluechange = false;
            BUS.TVC_MFMOVControl ctr = new TVC_MFMOVControl(PODInfo.Business_ID);
            DataTable dtVerify = ctr.GetVerify(ref sErr);
            DataRow dr4 = dtVerify.NewRow();
            dtVerify.Rows.Add(dr4);
            DataView dv4 = dtVerify.DefaultView;
            dv4.Sort = "Reference ASC";
            cboVerify.DataSource = dv4.ToTable();
            cboVerify.DisplayMember = "Reference";
            cboVerify.ValueMember = "Reference";
            cboVerify.SelectedValue = _strcboVerify;
            _isvaluechange = true;
        }
        protected override void afterAddNew()
        {
            _isvaluechange = false;
            //_processStatusLocal = strAction;
            //BUS.TVC_LOOKUPControl lookup = new BUS.TVC_LOOKUPControl(PODInfo.Business_ID);
            //string tableTVC_MFMOV = "TVC_MFMOVPRV";
            //if (PODInfo.Business_ID == "HV")
            //{
            //    tableTVC_MFMOV = "TVC_MFMOVHVJ";
            //}
            //dtHeld = lookup.GetQuery("SELECT Reference FROM " + tableTVC_MFMOV + " WHERE (((Hold)='Y')) GROUP BY Reference ORDER BY Reference", ref sErr);
            //DataRow dr2 = dtHeld.NewRow();
            //dtHeld.Rows.Add(dr2);
            //DataView dv = dtHeld.DefaultView;
            //dv.Sort = "Reference ASC";
            //cboHeld.DataSource = dv.ToTable();
            //cboHeld.SelectedValue = _strcboHeld;
            //dtPosted = lookup.GetQuery("SELECT Reference, PostCode,(Reference + ' - ' + PostCode) as DisplayCBO,SUNStatus FROM " + tableTVC_MFMOV + " GROUP BY Reference, PostCode, SUNStatus HAVING (((PostCode)<>'Z') 	AND ((SUNStatus)='N')) ORDER BY PostCode", ref sErr);
            //DataRow dr3 = dtPosted.NewRow();
            //dtPosted.Rows.Add(dr3);
            //DataView dv2 = dtPosted.DefaultView;
            //dv2.Sort = "PostCode ASC";
            //cboPosted.DataSource = dv2.ToTable();
            //cboPosted.SelectedValue = _strcboPosted;
            LoadPostCombo();
            LoadHeldCombo();
            LoadVerifyCombo();
            _isvaluechange = true;
        }
        protected override ErrorStatus validateForm(ref string sErr)
        {

            sErr += ValidMovement();
            string sWarn = "";
            ErrorStatus result = ErrorStatus.SUCCESS;
            if (sErr == "")
            {
                DTO.TVC_MFMOVInfo info = GetData();
                DataTable dt = info.ToDataTable();
                DataRow dr = info.ToDataRow(dt);
                dt.Rows.Add(dr);
                string sErr1 = "";

                int _sErrValid_Rul = RuleProCtr.Valid_Rule("TVC_MFMOV", dt, ref sErr1);

                if (_sErrValid_Rul != 1 && sErr1 != "")
                {
                    sWarn += sErr1;
                }
                else if (_sErrValid_Rul == 1)
                {
                    if (sErr1 == "") sErr = "ERROR";
                    else sErr = sErr1;
                }
            }

            if (sErr != "") result = ErrorStatus.ERROR;
            else if (sWarn != "") result = ErrorStatus.WARNING;

            sErr = string.Format("{0}{1}", sErr, sWarn);

            return result;
        }

        //private string ValidItem()
        //{
        //    string aYYMM = null;
        //    DateTime dtp = dtpMovementDate.Value;
        //    aYYMM = dtp.ToString("yyMM");// Strings.Right(Year(Nz(this.txtTransDate, "1900/01/01")), 2) + Strings.Format(Month(Nz(this.txtTransDate, "1900/01/01")), "00";
        //    if (txtReference.Text.ToString().Substring(2, 4) != aYYMM)
        //    {
        //        sErr = "Please enter Transaction Ref. in accordance with Transaction Date (XXYYMM-XXX).";
        //    }

        //    return sErr;
        //}

        private string CheckType(DataTable dtType)
        {
            sErr = "";
            if (dtType.Rows.Count >= 1)
            {
                sErr = " There are 2 movement types in the " + txtReference.Text + " reference, please check \n ";
            }
            return sErr;
        }

        protected override bool checkExists()
        {
            _strsErrcheckExists = " This reference has already been used! ";
            BUS.TVC_MFMOVControl ctr = new BUS.TVC_MFMOVControl(PODInfo.Business_ID);
            return ctr.IsExist(strCode);
        }

        //protected override ErrorStatus beforeAdd(ref string sErr)
        //{
        //    ErrorStatus result = ErrorStatus.SUCCESS;
        //    string tableTVC_MFMOV = "TVC_MFMOVPRV";
        //    if (PODInfo.Business_ID == "HV")
        //    {
        //        tableTVC_MFMOV = "TVC_MFMOVHVJ";
        //    }
        //    BUS.TVC_LOOKUPControl lookup = new BUS.TVC_LOOKUPControl(PODInfo.Business_ID);
        //    dtSumQty = lookup.GetQuery("SELECT * FROM " + tableTVC_MFMOV + " WHERE (PostCode<>'Z') ", ref sErr);
        //    sErr = CheckRef(dtSumQty);
        //    if (sErr != "")
        //        result = ErrorStatus.ERROR;

        //    return result;
        //}
        protected override string addRecord(bool isDraft = false)
        {
            string sDisp = "";
            string sErr = "";
            //sErr = ValidItem();
            //if (sErr != "")
            //{
            //    return sErr;
            //}
            BUS.TVC_MFMOVControl ctr = new BUS.TVC_MFMOVControl(PODInfo.Business_ID);
            DTO.TVC_MFMOVInfo info = GetData();
            BUS.SNSControl snsCtr = new BUS.SNSControl();

            object trans = ctr.BeginTransaction(ref sErr);
            Doclink._trans = trans;
            Doclink.Copy(info.Reference);
            if (sErr == "") Doclink.Update(info.Reference);
            //info.Code = snsCtr.GetCodeGen(MainForm.DB, "MME", ref sErr);
            info.Code = GetCode();
            info.PostCode = "Z";
            info.Hold = "Y";
            info.SUNStatus = "N";
            info.CreatedBy = PODInfo.USER_ID;
            info.CreatedDate = DateTime.Now;
            //if (_Post == true && info.Verified != "Y")
            //{
            //    sErr = txtReference.Text.Trim() + " has not been verified! ";
            //}
            if (sErr == "")
            {
                ctr.Add(info, ref sErr);
                sErr = ctr.UpdateRef(info);
            }

            if (sErr == "")
            {
                DataTable dtItemAve = ctr.GetbyReference(txtReference.Text, null, ref sDisp);

                if (sErr == "")
                {
                    int _sErrValid_Rul = RuleProCtr.Valid_Rule("TVC_MFMOV", dtItemAve, ref sDisp);
                    if (_sErrValid_Rul == 1)
                    {
                        if (sDisp == "") sDisp = "ERROR:" + sDisp;
                    }
                    else if (sDisp != "")
                    {
                        sDisp = "WARNING:" + sDisp;
                    }
                }
            }

            if (sErr == "")
            {

                DTO.SNSInfo snsInf = snsCtr.Get(MainForm.DB, "MME", ref sErr);
                int next = Convert.ToInt32(snsInf.NEXT_NUMBER);
                if (snsInf.ResetMonth == 1 && snsInf.MODIFIEDDATE.ToString().Substring(0, 6) != DateTime.Now.ToString("yyyy") + DateTime.Now.ToString("MM"))
                {
                    snsInf.NEXT_NUMBER = Convert.ToString(next + 1);
                }
                snsInf.NEXT_NUMBER = Convert.ToString(next + 1);
                snsInf.MODIFIEDDATE = Convert.ToInt32(DateTime.Now.ToString("yyyy") + DateTime.Now.ToString("MM") + DateTime.Now.ToString("dd"));
                snsCtr.SetTransaction(trans);
                sErr = snsCtr.InsertUpdate(snsInf);

                if (sErr == "")
                {
                    _infoDetail = info;
                    ctr.CommitTransaction(ref sErr);
                    if (sDisp != "")
                        MessageBox.Show(sDisp, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning, false);
                }
            }
            else
            {
                ctr.RollbackTransaction(ref sErr);
            }
            //if (_Post == true && info.PostCode == "Z" && sErr == "")
            //{
            //    sErr = Post(ctr, info.Reference, info);
            //}
            BalRef(info.Reference);
            return sErr;
        }

        protected override string updateRecord(bool isDraft = false)
        {
            string sDisp = "";
            string sErr = "";
            BUS.TVC_MFMOVControl ctr = new BUS.TVC_MFMOVControl(PODInfo.Business_ID);
            DTO.TVC_MFMOVInfo info = GetData();
            object trans = ctr.BeginTransaction(ref sErr);
            //if (_PostCode == null || _PostCode == "Z")
            //{
            //}
            //else
            //{
            //    info.PostCode = _PostCode;
            //    info.Hold = "";
            //    info.SUNStatus = "N";
            //}

            info.PostCode = "Z";
            if (info.Hold == "")
                info.Hold = "Y";
            info.SUNStatus = "N";

            info.ModifiedBy = PODInfo.USER_ID;
            info.ModifiedDate = DateTime.Now;
            Doclink._trans = trans;
            //if (_Post == true && info.Verified != "Y")
            //{
            //    sErr = txtReference.Text.Trim() + " has not been verified! ";
            //}
            if (sErr == "") Doclink.Update(info.Reference);
            if (sErr == "") sErr = ctr.Update(info);
            if (sErr == "") sErr = ctr.UpdateRef(info);

            if (sErr == "")
            {
                DataTable dtItemAve = ctr.GetbyReference(txtReference.Text, null, ref sDisp);

                if (sErr == "")
                {
                    int _sErrValid_Rul = RuleProCtr.Valid_Rule("TVC_MFMOV", dtItemAve, ref sDisp);
                    if (_sErrValid_Rul == 1)
                    {
                        if (sDisp == "") sDisp = "ERROR:" + sDisp;
                    }
                    else if (sDisp != "")
                    {
                        sDisp = "WARNING:" + sDisp;
                    }
                }
            }

            if (sErr == "")
            {
                _infoDetail = info;
                _Verified = _infoDetail.Verified;
                ctr.CommitTransaction(ref sErr);
                if (sDisp != "")
                    MessageBox.Show(sDisp, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning, false);

            }
            else ctr.RollbackTransaction(ref sErr);

            bool isConfirm = false;
            //if (_Post == true && info.PostCode == "Z" && sErr == "")
            //{
            //    sErr = Post(ctr, info.Reference, info, ref isConfirm);
            //}
            if (!isConfirm) BalRef(info.Reference);
            return sErr;
        }

        protected override string delRecord()
        {
            BUS.TVC_MFMOVControl ctr = new BUS.TVC_MFMOVControl(PODInfo.Business_ID);
            DTO.TVC_MFMOVInfo info = new DTO.TVC_MFMOVInfo((DataRowView)dgvList.CurrentRow.DataBoundItem);
            if (info.PostCode == "Z" && info.ANAL_M0 != "Y")
            {
                DataTable dt = ctr.GetbyReference(info.Reference, null, ref sErr);
                object trans = ctr.BeginTransaction(ref sErr);
                if (dt.Rows.Count <= 1)
                {
                    Doclink._trans = trans;
                    Doclink.Copy(info.Reference);
                    if (sErr == "") Doclink.Delete(info.Reference);
                }
                sErr = ctr.Delete(strCode);

                if (sErr == "")
                {

                    ctr.CommitTransaction(ref sErr);
                    BalRef(info.Reference);
                    _isvaluechange = false;
                    //_processStatusLocal = strAction;
                    BUS.TVC_LOOKUPControl lookup = new BUS.TVC_LOOKUPControl(PODInfo.Business_ID);
                    string tableTVC_MFMOV = "TVC_MFMOVPRV";
                    if (PODInfo.Business_ID == "HV")
                    {
                        tableTVC_MFMOV = "TVC_MFMOVHVJ";
                    }
                    dtHeld = lookup.GetQuery("SELECT Reference FROM " + tableTVC_MFMOV + " WHERE (((Hold)='Y')) GROUP BY Reference ORDER BY Reference", ref sErr);
                    DataRow dr2 = dtHeld.NewRow();
                    dtHeld.Rows.Add(dr2);
                    DataView dv = dtHeld.DefaultView;
                    dv.Sort = "Reference ASC";
                    cboHeld.DataSource = dv.ToTable();
                    cboHeld.SelectedValue = _strcboHeld;

                }
                else
                    ctr.RollbackTransaction(ref sErr);
            }
            else
            {
                sErr = "This code reference " + info.Reference + " has been used";
                //if (info.ANAL_M0 == "Y")
                //    MessageBox.Show(" Ban khong the xoa Movement duoc chuyen tu PO ", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, false);
                //else
                //    sErr = "This code reference " + info.Reference + " has been used";
                //MessageBox.Show(" This code reference " + info.Reference + " has been used ", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, false);
            }
            return sErr;
        }

        protected override void loadRecord(object o)
        {
            if (o is DataRowView)
            {
                DTO.TVC_MFMOVInfo inf = new DTO.TVC_MFMOVInfo((DataRowView)o);
                SetData(inf);
            }
        }


        private string CheckRef()
        {
            string sErr = "";
            BUS.TVC_MFMOVControl ctr = new TVC_MFMOVControl(GetMainForm().PODInfo.Business_ID);
            if (_infoDetail == null || (_infoDetail.PostCode == "Z" && _infoDetail.PostCode == ""))
            {
                if (ctr.HasRefInPost(GetMainForm().PODInfo.Business_ID, txtReference.Text, MovementType.Value + ""))
                {
                    sErr += " This reference has already been used! \n ";
                }
                if (ctr.Has2Ref(GetMainForm().PODInfo.Business_ID, txtReference.Text, MovementType.Value + ""))
                {
                    sErr += " There are 2 movement types in the " + txtReference.Text + " reference, please check \n ";
                }
            }

            return sErr;
        }

        /*
        private string Valid_Rule(string aTable, DataTable dttemp)
        {
            string strErr = "";
            int isErr = 0;
            bool X = false;
            BUS.RuleProfileControl RulePro = new BUS.RuleProfileControl(PODInfo.Business_ID);
            DataTable dt = new DataTable();
            dt = RulePro.GetMaster(aTable, ref sErr);
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    int isErr1 = 0;
                    BUS.RuleSetControl RuleSet = new BUS.RuleSetControl(PODInfo.Business_ID);
                    DataTable dtRuleSet = new DataTable();
                    for (int j = 0; j < 10; j++)
                    {
                        string errStr1 = "";
                        string aField = "";
                        string strquery = "";
                        string aCol = "COL" + j;
                        string strWhere = " ( COL" + j + " = 'Y' OR  COL" + j + " = 'N' OR  COL" + j + " = 'X' )";
                        dtRuleSet = RuleSet.GetbyRuleSetCode(dt.Rows[i]["RULESET_CODE"].ToString(), strWhere, ref sErr);
                        if (dtRuleSet.Rows.Count > 0)
                        {
                            for (int l = 0; l < dtRuleSet.Rows.Count; l++)
                            {
                                if (dtRuleSet.Rows[l][aCol].ToString().ToUpper() == "Y")
                                {

                                    if (dtRuleSet.Rows[l]["COMMAND"].ToString().ToUpper() == "IF")
                                    {
                                        strquery = strquery + ") AND (";
                                    }
                                    else
                                    {
                                        strquery = strquery + "   OR  ";
                                    }
                                    if (dtRuleSet.Rows[l]["START"].ToString() != "0" && dtRuleSet.Rows[l]["START"].ToString() != "")
                                    {
                                        aField = " SUBSTRING(" + dtRuleSet.Rows[l]["FIELD"].ToString() + ", " + dtRuleSet.Rows[l]["START"].ToString() + (dtRuleSet.Rows[l]["LENGTH"] == null ? "0" : ", " + dtRuleSet.Rows[l]["LENGTH"].ToString()) + ")";
                                    }
                                    else
                                    {
                                        aField = dtRuleSet.Rows[l]["FIELD"].ToString();
                                    }
                                    switch (dtRuleSet.Rows[l]["OPERATOR"].ToString())
                                    {
                                        case "SPACE":
                                            strquery = strquery + "(" + aField + " is null OR TRIM(" + dtRuleSet.Rows[l]["FIELD"].ToString() + ")='') ";
                                            break;
                                        case "EXISTS":
                                            strquery = strquery + "(" + aField + " is not null AND TRIM(" + dtRuleSet.Rows[l]["FIELD"].ToString() + ")<>'') ";
                                            break;
                                        default:
                                            switch (dtRuleSet.Rows[l]["FIELD"].ToString())
                                            {
                                                case "Amount":
                                                case "Quantity":
                                                case "Period":
                                                case "Average":
                                                case "MINSTOCK":
                                                case "MAXSTOCK":
                                                    //Nummeric field
                                                    strquery = strquery + aField + " " + dtRuleSet.Rows[l]["OPERATOR"].ToString() + dtRuleSet.Rows[l]["VALUE"].ToString() + " ";
                                                    break;
                                                case "TransDate":
                                                case "ShipmentDate":
                                                    // Date field
                                                    DateTime aFieldtime = DateTime.ParseExact(aField, "ddMMyyyy", CultureInfo.InvariantCulture);
                                                    DateTime avaluetime = DateTime.ParseExact(dtRuleSet.Rows[l]["VALUE"].ToString(), "ddMMyyyy", CultureInfo.InvariantCulture);
                                                    strquery = strquery + aFieldtime.ToString("yyyyMMdd") + " " + dtRuleSet.Rows[l]["OPERATOR"].ToString() + " '" + avaluetime.ToString("yyyyMMdd") + "' ";
                                                    break;
                                                default:
                                                    // String field
                                                    strquery = strquery + aField + " " + dtRuleSet.Rows[l]["OPERATOR"].ToString() + " '" + dtRuleSet.Rows[l]["VALUE"].ToString() + "' ";
                                                    break;
                                            }
                                            break;
                                    }
                                }
                                else if (dtRuleSet.Rows[l][aCol].ToString().ToUpper() == "N")
                                {

                                    if (dtRuleSet.Rows[l]["COMMAND"].ToString().ToUpper() == "IF")
                                    {
                                        strquery = strquery + ") AND (";
                                    }
                                    else
                                    {
                                        strquery = strquery + "  AND  ";
                                    }
                                    if (dtRuleSet.Rows[l]["START"].ToString() != "0" && dtRuleSet.Rows[l]["START"].ToString() != "")
                                    {

                                        aField = " SUBSTRING(" + dtRuleSet.Rows[l]["FIELD"].ToString() + ", " + dtRuleSet.Rows[l]["START"].ToString() + (dtRuleSet.Rows[l]["LENGTH"] == null ? "0" : ", " + dtRuleSet.Rows[l]["LENGTH"].ToString()) + ")";
                                    }
                                    else
                                    {
                                        aField = dtRuleSet.Rows[l]["FIELD"].ToString();
                                    }
                                    switch (dtRuleSet.Rows[l]["OPERATOR"].ToString())
                                    {
                                        case "SPACE":
                                            strquery = strquery + " NOT (" + aField + " is null OR TRIM(" + dtRuleSet.Rows[l]["FIELD"].ToString() + ")='') ";
                                            break;
                                        case "EXISTS":
                                            strquery = strquery + " NOT (" + aField + " is not null AND TRIM(" + dtRuleSet.Rows[l]["FIELD"].ToString() + ")<>'') ";
                                            break;
                                        default:
                                            switch (dtRuleSet.Rows[l]["FIELD"].ToString())
                                            {
                                                case "Amount":
                                                case "Quantity":
                                                case "Period":
                                                case "Average":
                                                case "MINSTOCK":
                                                case "MAXSTOCK":
                                                    //Nummeric field
                                                    strquery = strquery + " NOT (" + aField + " " + dtRuleSet.Rows[l]["OPERATOR"].ToString() + dtRuleSet.Rows[l]["VALUE"].ToString() + ") ";
                                                    break;
                                                case "TransDate":
                                                case "ShipmentDate":
                                                    // Date field
                                                    DateTime aFieldtime = DateTime.ParseExact(aField, "ddMMyyyy", CultureInfo.InvariantCulture);
                                                    DateTime avaluetime = DateTime.ParseExact(dtRuleSet.Rows[l]["VALUE"].ToString(), "ddMMyyyy", CultureInfo.InvariantCulture);
                                                    strquery = strquery + " NOT (" + aFieldtime.ToString("yyyyMMdd") + " " + dtRuleSet.Rows[l]["OPERATOR"].ToString() + " '" + avaluetime.ToString("yyyyMMdd") + "') ";
                                                    break;
                                                default:
                                                    // String field
                                                    strquery = strquery + " NOT (" + aField + " " + dtRuleSet.Rows[l]["OPERATOR"].ToString() + " '" + dtRuleSet.Rows[l]["VALUE"].ToString() + "') ";
                                                    break;
                                            }
                                            break;
                                    }
                                }
                                else if (dtRuleSet.Rows[l][aCol].ToString().ToUpper() == "X")
                                {
                                    errStr1 = errStr1 + dtRuleSet.Rows[l]["VALUE"].ToString() + ".";
                                    if (dtRuleSet.Rows[l]["COMMAND"].ToString().ToUpper() == "ERROR")
                                        isErr1 = 1;
                                }
                            }

                            if (strquery != "")
                            {
                                strquery = "  (" + strquery.Substring(7, strquery.Length - 7) + ")";
                            }
                            string aItem = "";
                            // de lam sau
                            DataRow[] arrdr = dttemp.Select(strquery);
                            if (arrdr.Length > 0)
                            {
                                for (int n = 0; n < arrdr.Length; n++)
                                {
                                    X = true;
                                    aItem = aItem + " " + arrdr[n]["ItemCode"].ToString();
                                }
                                if (X)
                                {
                                    isErr = isErr + isErr1;
                                    if (!string.IsNullOrEmpty(errStr1))
                                        strErr = strErr + " \n " + ((aItem.Length) > 2 | true ? aItem.Substring(0, aItem.Length) + ": " : "") + errStr1;
                                }
                                else
                                    isErr = isErr + 0;
                            }
                            _sErrValid_Rul = isErr1;
                        }
                    }
                }
            }
            //if (strErr != "")
            //{
            //    MessageBox.Show(strErr, "Alert", MessageBoxButtons.OK, MessageBoxIcon.Warning, false);
            //}
            return strErr;
        }
        */

        private string Post(BUS.TVC_MFMOVControl ctr, string aRef, DTO.TVC_MFMOVInfo info, ref bool isConfirm)
        {
            try
            {
                //DataTable dtItemAve = ctr.GetQuery(Query, ref sErr);
                DataTable dtItemAve = ctr.GetbyReference(txtReference.Text, null, ref sErr);

                string sErrRule = "";
                int _sErrValid_Rul = RuleProCtr.Valid_Rule("TVC_MFMOV", dtItemAve, ref sErrRule);
                if (_sErrValid_Rul == 1 && sErrRule != "")
                {
                    sErr = sErrRule;
                }
                else if (_sErrValid_Rul != 1 && sErrRule != "")
                {
                    isConfirm = true;
                    MessageBox.Show(sErrRule, "Confirm", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, delegate(object newSender, EventArgs newArgs)
                    {
                        if (((MessageBoxWindow)newSender).DialogResult == DialogResult.OK)
                        {
                            DataTable dtSumQty = ctr.GetItemSumByRef(txtReference.Text, ref sErr);
                            if (sErr == "") sErr = PostStep2(ctr, ref info, dtItemAve, dtSumQty);
                            if (sErr == "")
                            {
                                //MessageBox.Show("This reference is posted successfully", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information, false);
                                reloadList();
                                enableForm(false);
                                _processStatus = "V";
                                SetupToolBar(_processStatus);
                                BalRef(txtReference.Text);
                            }
                            else
                            {
                                MessageBox.Show(sErr, "Error", MessageBoxButtons.OK, MessageBoxIcon.Information, false);
                            }
                        }
                        //else _processStatus = saveProcess;
                    }, false);
                }
                else
                {
                    DataTable dtSumQty = ctr.GetItemSumByRef(txtReference.Text, ref sErr);
                    if (sErr == "") sErr = PostStep2(ctr, ref info, dtItemAve, dtSumQty);
                    if (sErr == "")
                    {
                        lblHoldStatus.Text = "POSTED   " + info.PostCode;
                    }

                }
                return sErr;
            }
            catch (Exception ex)
            {

                return ex.Message;
            }
        }

        private string PostStep2(BUS.TVC_MFMOVControl ctr, ref DTO.TVC_MFMOVInfo info, DataTable dtItemAve, DataTable dtSumQty)
        {
            string _PostCode = "Z";
            string sErr = "";
            //DTO.TVC_MFMOVInfo infoRollback = info;

            DataTable MaxPostCode = ctr.GetMaxPostCode(ref sErr);
            object trans = ctr.GetTransaction();

            BUS.SNSControl snsCtr = new SNSControl();

            try
            {
                for (int i = 0; i < dtItemAve.Rows.Count; i++)
                {
                    if (sErr != "") break;
                    info = new DTO.TVC_MFMOVInfo(dtItemAve.Rows[i]);
                    if (_processStatusLocal != "A")
                    {
                        if (getPeriod(info.Period) == 0)
                        {
                            //MessageBox.Show(" Transacion date is out of range, please check! ", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information, false);
                            sErr += " Transacion date is out of range, please check! ";
                            return sErr;
                        }
                    }


                    //BkaAve_Cost[i] = aItemAve;
                    //BKItemCode[i] = info.ItemCode;
                    if (info.Quantity < 0)
                    {
                        BUS.TVC_RFITMControl ctra = new BUS.TVC_RFITMControl(PODInfo.Business_ID);
                        ctra.SetTransaction(trans);
                        double aItemAve = ctra.Get(info.ItemCode, ref sErr).Ave_Cost;
                        object objTmp = dtSumQty.Compute("SUM(Quantity)", string.Format("ItemCode = '{0}' AND Location='{1}'", info.ItemCode, info.Location));
                        int aQty = 0;

                        if (objTmp != DBNull.Value) aQty = Convert.ToInt32(objTmp); //StockQty(info.ItemCode, cboLocation.SelectedValue.ToString(), dtSumQty);
                        objTmp = dtSumQty.Compute("SUM(Quantity)", string.Format("ItemCode = '{0}'", info.ItemCode));

                        int aQtyAll = 0;
                        if (objTmp != DBNull.Value) aQtyAll = Convert.ToInt32(dtSumQty.Compute("SUM(Quantity)", string.Format("ItemCode = '{0}'", info.ItemCode))); //StockQty(info.ItemCode, cboLocation.SelectedValue.ToString(), dtSumQty);

                        if (aQty < Math.Abs(info.Quantity))
                        {
                            sErr += string.Format(" Insufficient quantity. At {0}, Item {1} remains only {2}", info.Location, info.ItemCode, aQty);
                            //MessageBox.Show(sErr);
                        }
                        else if (aQtyAll == Math.Abs(info.Quantity))
                        {
                            objTmp = dtSumQty.Compute("SUM(Amount)", string.Format("ItemCode = '{0}'", info.ItemCode));
                            double AmtAll = 0;
                            if (objTmp != DBNull.Value) AmtAll = Convert.ToDouble(objTmp); //StockQty(info.ItemCode, cboLocation.SelectedValue.ToString(), dtSumQty);

                            info.Amount = Math.Round(-1 * AmtAll, 2);
                            info.Average = Math.Round(info.Amount / info.Quantity, 5);
                        }
                        else
                        {
                            //double AmtAll = Convert.ToDouble(dtSumQty.Compute("SUM(Amount)", string.Format("ItemCode = '{0}'", info.ItemCode))); //StockQty(info.ItemCode, cboLocation.SelectedValue.ToString(), dtSumQty);

                            info.Average = aItemAve;

                            info.Amount = Math.Round(info.Average * info.Quantity, 2);
                        }

                        for (int k = 0; k < dtSumQty.Rows.Count; k++)
                        {
                            if (string.Format("{0}|{1}", info.ItemCode, info.Location) == string.Format("{0}|{1}", dtSumQty.Rows[k]["ItemCode"], dtSumQty.Rows[k]["Location"]))
                            {
                                dtSumQty.Rows[k]["Quantity"] = Convert.ToInt32(dtSumQty.Rows[k]["Quantity"]) + info.Quantity;
                                dtSumQty.Rows[k]["Amount"] = Convert.ToDouble(dtSumQty.Rows[k]["Amount"]) + info.Amount;
                                break;
                            }
                        }
                    }
                    else
                    {
                        info.Amount = Math.Round(info.Amount, 2);
                        object objTemp = dtSumQty.Compute("SUM(Quantity)", string.Format("ItemCode = '{0}'", info.ItemCode)).ToString() == "" ? 0 : dtSumQty.Compute("SUM(Quantity)", string.Format("ItemCode = '{0}'", info.ItemCode));
                        int remainQty = 0;
                        if (objTemp != DBNull.Value) remainQty = Convert.ToInt32(objTemp); //StockQty(info.ItemCode, cboLocation.SelectedValue.ToString(), dtSumQty);

                        objTemp = dtSumQty.Compute("SUM(Amount)", string.Format("ItemCode = '{0}'", info.ItemCode)).ToString() == "" ? 0 : dtSumQty.Compute("SUM(Amount)", string.Format("ItemCode = '{0}'", info.ItemCode));
                        Double AmtAll = 0;
                        if (objTemp != DBNull.Value) AmtAll = Convert.ToDouble(objTemp); //StockQty(info.ItemCode, cboLocation.SelectedValue.ToString(), dtSumQty);


                        int SumQty = remainQty + info.Quantity;
                        Double SumAmt = AmtAll + info.Amount;

                        if (SumQty == 0) info.Average = 0;
                        else info.Average = Math.Round(SumAmt / SumQty, 5);

                        bool flagEx = false;
                        for (int k = 0; k < dtSumQty.Rows.Count; k++)
                        {
                            if (string.Format("{0}|{1}", info.ItemCode, info.Location) == string.Format("{0}|{1}", dtSumQty.Rows[k]["ItemCode"], dtSumQty.Rows[k]["Location"]))
                            {
                                dtSumQty.Rows[k]["Quantity"] = Convert.ToInt32(dtSumQty.Rows[k]["Quantity"]) + info.Quantity;
                                dtSumQty.Rows[k]["Amount"] = Convert.ToDouble(dtSumQty.Rows[k]["Amount"]) + info.Amount;
                                flagEx = true;
                                break;
                            }
                        }

                        if (!flagEx)
                        {
                            dtSumQty.Rows.Add(info.ItemCode, info.Location, info.Quantity, info.Amount);
                        }

                    }

                    if (sErr == "")
                    {
                        info.Hold = "";
                        info.PostBy = PODInfo.USER_ID;
                        info.PostDate = DateTime.Now;
                        info.ModifiedDate = DateTime.Now;
                        info.ModifiedBy = PODInfo.USER_ID;
                        //
                        //if (_PostCode == "Z") _PostCode = snsCtr.GetCodeGen(MainForm.DB, "PostCode", ref sErr);
                        if (_PostCode == "Z") _PostCode = GetPostCode(MaxPostCode);
                        info.PostCode = _PostCode;
                    }

                    if (sErr == "") sErr = ctr.Update(info);


                    if (sErr == "" && info.Quantity > 0) sErr = UpdItemAverage(info.ItemCode, info.Average, trans);


                }
            }
            catch (Exception ex) { sErr = ex.Message; }



            if (sErr == "")
            {
                //snsCtr.SetTransaction(trans);
                //DTO.SNSInfo snsInf = snsCtr.Get(MainForm.DB, "PostCode", ref sErr);
                //int next = Convert.ToInt32(snsInf.NEXT_NUMBER);
                //if (snsInf.ResetMonth == 1 && snsInf.MODIFIEDDATE.ToString().Substring(0, 6) != DateTime.Now.ToString("yyyy") + DateTime.Now.ToString("MM"))
                //{
                //    snsInf.NEXT_NUMBER = Convert.ToString(next + 1);
                //}
                //snsInf.NEXT_NUMBER = Convert.ToString(next + 1);
                //snsInf.MODIFIEDDATE = Convert.ToInt32(DateTime.Now.ToString("yyyy") + DateTime.Now.ToString("MM") + DateTime.Now.ToString("dd"));
                //if (sErr == "") sErr = snsCtr.InsertUpdate(snsInf);
                _infoDetail.PostCode = _PostCode;
            }
            return sErr;
        }

        private string UpdItemAverage(string aItem, double aAve_Cost, object trans)
        {
            sErr = "";
            if (aItem != null)
            {
                BUS.TVC_RFITMControl ctr = new TVC_RFITMControl(PODInfo.Business_ID);
                ctr.SetTransaction(trans);
                ctr.Update(aItem, aAve_Cost, ref sErr);
            }
            return sErr;
        }
        private int StockQty(string aItem, string aLocation, DataTable dt)
        {
            DataRow[] dr = dt.Select("(ItemCode = '" + aItem + "') And (Location='" + aLocation + "')");
            _SumAmount = 0;
            if (dr.Length > 0)
            {
                int SumQty = 0;
                for (int i = 0; i < dr.Length; i++)
                {
                    SumQty += int.Parse(dr[i]["Quantity"].ToString());
                    _SumAmount += decimal.Parse(dr[i]["Amount"].ToString());
                }
                return SumQty;
            }
            else
                return 0;
        }

        private DTO.TVC_MFMOVInfo GetData()
        {
            _info = new DTO.TVC_MFMOVInfo();
            _info.Code = strCode;
            _info.TransDate = (DateTime)dtpMovementDate.Value;
            _info.Period = txtPeriod.Text == "" ? int.Parse(_info.TransDate.ToString("yyyy0MM")) : int.Parse(txtPeriod.Text.ToString());
            _info.Reference = txtReference.Text.Trim() == "" ? GetRef(_Prefix) : txtReference.Text.Trim();
            _info.To_ = cboTo.Text;
            _info.From_ = cboFrom.Text;
            _info.PINo = txtPino.Text.ToString();
            _info.POSOContract = cboPO.Value == null ? "" : cboPO.Value.ToString();
            _info.Supplier = Supplier.Value == null ? "" : Supplier.Value.ToString();
            _info.WellCode = cboWellCode.Value == null ? "" : cboWellCode.Value.ToString();
            _info.Department = cboDepartment.SelectedValue == null ? "" : cboDepartment.SelectedValue.ToString();
            _info.Remark = txtRemark.Text;
            _info.DeliveryPoint = cboDeliveryPoint.Text == null ? "" : cboDeliveryPoint.Text.ToString();
            _info.ShipmentDate = (DateTime)dtpShipmentDate.Value;
            _info.BLAWBNo = txtBLAWB.Text;
            _info.Type = MovementType.Value == null ? "" : MovementType.Value.ToString();
            _info.ShipmentBy = cboShipmentby.Text.ToString();
            _info.Quantity = int.Parse(numQuantity.Value.ToString());
            _info.Amount = float.Parse(numAmount.Value.ToString());
            _info.ItemCode = ItemCode.Value == null ? "" : ItemCode.Value.ToString();
            _info.Location = cboLocation.Value == null ? "" : cboLocation.Value.ToString();
            _info.PartNo = cboPartNo.Text == null ? "" : cboPartNo.Text.ToString();
            _info.SerialNo = cboSerialNo.Text == null ? "" : cboSerialNo.Text.ToString();
            _info.Status = cboStatus.SelectedValue == null ? "" : cboStatus.SelectedValue.ToString();
            _info.BINNo = cboBinNum.SelectedValue == null ? "" : cboBinNum.SelectedValue.ToString();
            _info.Account = cboAccountCode.Text == null ? "" : cboAccountCode.Text.ToString();
            setAmountAverageQty(_info, dtSumQty);
            _info.Intransit = chkIntransit.Checked == true ? "Y" : "";
            _info.Verified = _Verified;
            _info.CreatedBy = _CreatedBy;
            //_info.Verified = chkIntransit.Checked == true ? "Y" : "";
            return _info;
        }
        string _CreatedBy = "";
        private void setAmountAverageQty(DTO.TVC_MFMOVInfo info, DataTable dt)
        {
            double remainQty = 0;
            double SumQty = 0;
            double aItemAve = 0;
            double SumAmt = 0;
            if (_Mark == "" || info.ItemCode == "")
            {
                return;
            }
            aItemAve = getItemAverage(info.ItemCode);
            //issue, calculate Amount and Average values
            if (_Mark == "-")
            {

                info.Quantity = -1 * Math.Abs(info.Quantity);
                info.Amount = Math.Round(aItemAve * info.Quantity, 2);
                info.Average = aItemAve;
                numAmount.Value = (decimal)info.Amount;
                //receipt, only calculate Average value
            }
            else
            {
                info.Quantity = info.Quantity;
                info.Amount = Math.Round(info.Amount, 2);
                remainQty = UnitInStock(info.ItemCode, dt);
                SumQty = remainQty + info.Quantity;
                SumAmt = aItemAve * remainQty + info.Amount;
                if (SumQty == 0)
                    info.Average = 0;
                else
                    info.Average = Math.Round(SumAmt / SumQty, 5);
            }
        }

        private double UnitInStock(string aItem, DataTable dt)
        {
            DataRow[] dr = dt.Select("(ItemCode = '" + aItem + "') ");

            if (dr.Length > 0)
            {
                int SumQty = 0;
                for (int i = 0; i < dr.Length; i++)
                {
                    SumQty += int.Parse(dr[i]["Quantity"].ToString());
                }
                return SumQty;
            }
            else
                return 0;
        }

        private double getItemAverage(string Item)
        {
            BUS.TVC_RFITMControl ctr = new BUS.TVC_RFITMControl(PODInfo.Business_ID);
            return ctr.Get(Item, ref sErr).Ave_Cost;
        }

        private string ValidMovement()
        {

            string strErr = "";

            if (MovementType.Text.Trim() == "")
            {
                strErr = strErr + "Movement type, ";

            }
            if (dtpMovementDate.Value.ToString().Trim() == "")
            {
                strErr = strErr + "Transaction date, ";
            }
            if (this.txtReference.Text == "")
            {
                strErr = strErr + "Reference, ";
            }
            if (dtpShipmentDate.Value.ToString().Trim() == "")
            {
                strErr = strErr + " Shipment date, ";

            }
            if (ItemCode.Value.ToString().Trim() == "")
            {
                strErr = strErr + " Item code, ";
            }
            if (this.cboLocation.Text == "")
            {
                strErr = strErr + " Location, ";
            }

            if (_CreatedBy != "Migration" && (this.cboAccountCode.Value.ToString() == "" || this.cboAccountCode.Text.Trim().Length > 5))
            {
                strErr = strErr + " Account, ";
            }

            if (strErr != "")
                strErr += " cannot be blank, please check! \n ";

            DateTime dtpMD = (DateTime)dtpMovementDate.Value;
            txtPeriod.Text = getPeriod(int.Parse(dtpMD.Year.ToString() + ("000" + dtpMD.Month.ToString()).Substring(("000" + dtpMD.Month.ToString()).Length - 3, 3))).ToString();
            if (txtPeriod.Text == "0")
            {
                strErr = " Transacion date is out of range, please check! \n ";
            }
            if (_infoDetail == null || _infoDetail.PostCode == "Z")
            {

                DateTime dtp = (DateTime)dtpMovementDate.Value;
                string aYYMM = null;
                aYYMM = dtp.ToString("yyMM");
                if (txtReference.Text.Substring(2, 4) != aYYMM)
                {
                    if (strErr.Length > 4)
                    {
                        strErr = strErr + " Please enter Transaction Ref. in accordance with Transaction Date (XXYYMM-XXX). \n";
                    }
                    else
                    {
                        strErr += "Please enter Transaction Ref. in accordance with Transaction Date (XXYYMM-XXX).\n ";
                    }
                }

                strErr += CheckRef();

            }
            return strErr;
        }

        private int getPeriod(int aPeriod)
        {
            int functionReturnValue;
            int aPeriodF = 0;
            int aPeriodT = 0;
            CommonControl a = new CommonControl();
            DateTime now = DateTime.Now;
            string sErr = "";
            BUS.BUDControl busCtr = new BUDControl();


            DTO.GlobalParametersInfo Gloinfo = new DTO.GlobalParametersInfo();
            Gloinfo = busCtr.get(ref sErr);

            aPeriodF = int.Parse(Gloinfo.PeriodFrom.ToString());
            aPeriodT = int.Parse(Gloinfo.PeriodTo.ToString());

            if (aPeriod < aPeriodF | aPeriod > aPeriodT)
                functionReturnValue = 0;
            else
                functionReturnValue = aPeriod;
            return functionReturnValue;
        }

        private void BgEdit()
        {
            foreach (Control x in pnDetail.Controls)
            {
                if (x is TextBox || x is ComboBox || x is TVC.Modules.CustomControl.MultiColumnCombo || x is NumericUpDown || x is DatePicker || x is ComboBox || x is CustomControl.LookupBox || x is CustomControl.DateTimeCustom)
                {
                    if (x.Name != "txtPeriod")
                    {
                        x.ForeColor = System.Drawing.Color.Black;
                    }
                }
            }

        }

        protected override void enableForm(bool p)
        {
            _btnPost = p;
            foreach (Control x in pnDetail.Controls)
            {

                if (x is TextBox || x is ComboBox || x is TVC.Modules.CustomControl.MultiColumnCombo || x is NumericUpDown || x is DatePicker || x is ComboBox || x is CustomControl.LookupBox || x is CustomControl.DateTimeCustom)
                {
                    if (x.Name != "txtPeriod" && x.Name != "lblItemCode")
                    {
                        x.Enabled = p;
                        //x.ForeColor = System.Drawing.Color.Black;
                        //x.BackColor = System.Drawing.Color.White;
                    }
                }
                lblItemCode.Enabled = false;
                lblItemCode.BackColor = System.Drawing.Color.White;
                txtPeriod.Enabled = false;
                cboDepartment.Enabled = false;
                Doclink.Enabled = p;
                chkIntransit.Enabled = p;
                //btnDetail.Enabled = false;

            }
        }

        protected override void refreshForm(string str)
        {
            _isvaluechange = false;
            strCode = str;
            lblHoldStatus.Text = "";
            txtPeriod.Text = str;
            txtReference.Text = str;
            cboTo.Text = str;
            cboFrom.SelectedValue = str;
            txtPino.Text = str;
            cboPO.Value = str;
            Supplier.Value = str;
            cboWellCode.Value = str;
            cboDepartment.SelectedValue = str;
            txtRemark.Text = str;
            cboDeliveryPoint.SelectedValue = str;
            dtpMovementDate.Value = DateTime.Now;
            dtpShipmentDate.Value = DateTime.Now;
            txtBLAWB.Text = str;
            MovementType.Value = str;
            cboShipmentby.SelectedValue = str;
            ItemCode.Value = str;
            cboPartNo.SelectedValue = str;
            cboSerialNo.SelectedValue = str;
            cboStatus.SelectedValue = str;
            cboLocation.Value = str;
            cboBinNum.SelectedValue = str;
            //cboAccountCode.Value = str;
            numAmount.Value = 0;
            numQuantity.Value = 0;
            ItemCode.Value = str;
            cboPartNo.SelectedValue = str;
            cboSerialNo.SelectedValue = str;
            cboStatus.SelectedValue = str;
            cboLocation.Value = str;
            cboBinNum.SelectedValue = str;
            cboAccountCode.Value = str;
            numAmount.Value = 0;
            numQuantity.Value = 0;
            //Doclink.Initialization(GetMainForm().PODInfo.Business_ID.ToString().Trim(), _strType, "", GetMainForm());
            Doclink.Clear();
            lblItemCode.Text = "";
            lblMovementType.Text = "";
            chkIntransit.Checked = false;
            //Doclink.Initialization(GetMainForm().PODInfo.Business_ID.ToString().Trim(), _strType, "", GetMainForm());
            _isvaluechange = true;
        }

        private void DeleteRef()
        {
            if (dgvList.CurrentCell != null)
            {
                DTO.TVC_MFMOVInfo info = new DTO.TVC_MFMOVInfo((DataRowView)dgvList.CurrentRow.DataBoundItem);
                //MessageBox.Show(sErr, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning, false);

                if (info.PostCode == "Z")
                {
                    if (info.ANAL_M0 == "Y")
                    {
                        sErr = RefreshPOSUN(info);
                    }
                    if (sErr == "")
                    {
                        MessageBox.Show(" Are you sure to delete all items of " + info.Reference + " reference?", "Confirm", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, delegate(object newSender, EventArgs newArgs)
                        {
                            if (((MessageBoxWindow)newSender).DialogResult == DialogResult.OK) DeleteStep2(info);
                            //else _processStatus = saveProcess;
                        }, false);
                    }
                }
                //}
                //else
                //{
                //if (info.PostCode == "Z")
                //    MessageBox.Show(" Ban khong the xoa Movement duoc chuyen tu PO ", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, false);
                //else
                //    MessageBox.Show(" This code reference " + info.Reference + " has been used ", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, false);

                //}
                //MessageBox.Show("This code reference " + info.Reference + " has been used");

            }

        }

        private string RefreshPOSUN(DTO.TVC_MFMOVInfo info)
        {
            string DTB = Properties.Settings.Default.SUNHL;
            //string Connec = MainForm.HLConnect;
            string Table = "SPMFDET" + Properties.Settings.Default.SUNHL;
            if (PODInfo.Business_ID == "HV")
            {
                DTB = Properties.Settings.Default.SUNHV;
                Table = "SPMFDET" + Properties.Settings.Default.SUNHV;
                //Connec = MainForm.HVConnect;
            }
            string Query = "";
            Query = " UPDATE " + Table +
" SET [ASSET_CODE] =''" +
      ",[ASSET_SUB] =''" +
      ",[ASSET_IND] =''" +
       "  Where ASSET_CODE = '" + info.ANAL_M1 + "'";
            BUS.CommonControl _impo = new BUS.CommonControl();
            _impo.executeQuery(_Connecstr, Query, ref sErr);

            return sErr;
        }

        private void DeleteStep2(DTO.TVC_MFMOVInfo info)
        {
            //MessageBox.Show(" Are you sure? ", "Confirm", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, delegate(object newSender, EventArgs newArgs)
            //{
            //    if (((MessageBoxWindow)newSender).DialogResult == DialogResult.OK)
            //    {
            BUS.TVC_MFMOVControl ctr = new BUS.TVC_MFMOVControl(PODInfo.Business_ID);


            //Forms.frmMsg frm = new Forms.frmMsg();
            //frm.FormClosed += delegate(object form, FormClosedEventArgs args)
            //{
            //if (((Gizmox.WebGUI.Forms.Form)form).DialogResult == DialogResult.OK)
            //{
            object trans = ctr.BeginTransaction(ref sErr);
            ctr.DeleteRef(info.Reference);
            Doclink._trans = trans;
            Doclink.Copy(info.Reference);
            if (sErr == "") sErr = Doclink.Delete(info.Reference);
            if (sErr == "")
            {
                //GetMainForm().RemoveRecord(_strType, ((DataRowView)dgvDataSource.CurrentRow.DataBoundItem).Row);
                ctr.CommitTransaction(ref sErr);
                refresh();
                sErr = String.Format(clsConfigurarion.GetErrMsg("E0010", language), info.Reference);
                //frm.ShowMsg(String.Format("You could not delete blank movement!", info.Code));
            }
            else
            {
                ctr.RollbackTransaction(ref sErr);
            }

            ThrowMsg(sErr);
            //    }

            //};
            //frm.ShowMsg(String.Format(clsConfigurarion.GetErrMsg("E0011", language), info.Reference));
            //frm.ShowMsg(String.Format("You could not delete blank movement!", info.Code));


            //    }
            //    //else _processStatus = saveProcess;
            //});

        }

        protected override void reloadList()
        {
            if (_processStatusLocal != "A" && _reload == false)
            {
                _strFilter = " Reference = '" + txtReference.Text + "'  ";
                if (txtReference.Text.Trim() != "")
                    BalRef(txtReference.Text.Trim());
            }
            int intpage = dgvList.CurrentPage;
            string sErr = "";
            BUS.TVC_MFMOVControl MMQCtr = new BUS.TVC_MFMOVControl(PODInfo.Business_ID);
            DataTable dtb = null;
            dtb = MMQCtr.GetbyFilter(_strFilter, ref sErr);
            bisMME.DataSource = dtb;
            double maxrow = Convert.ToDouble(dtb.Rows.Count) / Convert.ToDouble(dgvList.ItemsPerPage);
            if (maxrow >= intpage - 0.9)
            {
                dgvList.CurrentPage = intpage;
            }
        }


        private void MMEN_Load(object sender, EventArgs e)
        {

            gridFilter1.LoadData(GetMainForm().PODInfo.USER_ID, "MovementEntry", "TVC_MFMOV", PODInfo.Business_ID);
            gridFilter1.panYear.Visible = false;
            gridFilter1.btnOK_Click(sender, e);
            enableForm(false);
            refreshForm("");
            RuleProCtr = new BUS.RuleProfileControl(PODInfo.Business_ID);
            //MovementType.Focus();
        }

        private void UpdateSunStatus()
        {
            string TableMOV = "TVC_MFMOV" + Properties.Settings.Default.SUNHL;
            if (PODInfo.Business_ID == "HV")
            {

                TableMOV = "TVC_MFMOV" + Properties.Settings.Default.SUNHV;
            }
            TVC.ClassDiagram.SUNDBDataContext db1 = new TVC.ClassDiagram.SUNDBDataContext(_Connecstr);
            TVC.ClassDiagram.TVCDataContext db2 = new TVC.ClassDiagram.TVCDataContext();
            if (PODInfo.Business_ID == "HV")
            {
                var result1 = (from e in db2.TVC_MFMOVHVJs
                               where (e.SUNStatus.ToString() != "Y")
                               select e.Reference
                  ).ToList();

                var result2 = (from b in db1.SMMFMOVHVJs
                               where ((from m in result1
                                       select m.Trim()).Contains(b.MVMNT_REF))
                               select b.MVMNT_REF
                  ).ToList();

                if (result2.Count > 0)
                {
                    for (int i = 0; i < result2.Count; i++)
                    {
                        //item[]
                        BUS.TVC_MFMOVControl ctr = new TVC_MFMOVControl(PODInfo.Business_ID);
                        string SQL = "Update " + TableMOV + " set SUNStatus='Y' where Ltrim(Rtrim(Reference)) = '" + result2[i].Trim() + "'";
                        ctr.GetQuery(SQL, ref sErr);
                    }
                }
            }
            else
            {
                var result1 = (from e in db2.TVC_MFMOVPRVs
                               where (e.SUNStatus.ToString() != "Y")
                               select e.Reference
                   ).ToList();

                var result2 = (from b in db1.SMMFMOVPRVs
                               where ((from m in result1
                                       select m.Trim()).Contains(b.MVMNT_REF))
                               select b.MVMNT_REF
                  ).ToList();

                if (result2.Count > 0)
                {
                    for (int i = 0; i < result2.Count; i++)
                    {
                        //item[]
                        BUS.TVC_MFMOVControl ctr = new TVC_MFMOVControl(PODInfo.Business_ID);
                        string SQL = "Update " + TableMOV + " set SUNStatus='Y' where Ltrim(Rtrim(Reference)) = '" + result2[i].Trim() + "'";
                        ctr.GetQuery(SQL, ref sErr);
                    }
                }
            }

        }



        public BindingSource bsCombo = new BindingSource();
        //private bool _Post;
        private string _Verified;
        private DTO.TVC_MFMOVInfo _infoDetail;

        public void LoadCombo()
        {
            GetMainForm();
            BUS.TVC_LOOKUPControl lookup = new BUS.TVC_LOOKUPControl(PODInfo.Business_ID);
            BUS.TVC_RFITMControl rfitm = new BUS.TVC_RFITMControl(PODInfo.Business_ID);
            string tableTVC_MFMOV = "TVC_MFMOVPRV";
            string tableTVC_MVP = "TVC_MVPPRV";
            string DTBSUN = Properties.Settings.Default.SUNHL;
            if (PODInfo.Business_ID == "HV")
            {
                tableTVC_MFMOV = "TVC_MFMOVHVJ";
                tableTVC_MVP = "TVC_MVPHVJ";
                DTBSUN = Properties.Settings.Default.SUNHV;
            }

            // Movement Type

            DataTable dtMovementType = lookup.GetQuery("SELECT Code, Lookup, Mark, Description, From_, To_, ItemCode, Status, Amount, POSOContract, Location, Account, Supplier, WellCode, Department, Template, Prefix FROM " + tableTVC_MVP + " WHERE Suppend is Null or Suppend=0 ", ref sErr);
            DataRow dr = dtMovementType.NewRow();
            dtMovementType.Rows.Add(dr);
            MovementType.DisplayMember = "Code";
            MovementType.ValueMember = "Code";
            MovementType.MainForm = GetMainForm();
            MovementType.Lookup = "MovenentType";
            MovementType.DataSource = dtMovementType;




            // Shipment By

            DataTable dtShipmentBy = lookup.GetQuery(" SELECT DISTINCT ShipmentBy FROM " + tableTVC_MFMOV + " ORDER BY ShipmentBy ", ref sErr);
            DataRow dr1 = dtShipmentBy.NewRow();
            dtShipmentBy.Rows.Add(dr1);

            cboShipmentby.DataSource = dtShipmentBy;
            cboShipmentby.DisplayMember = "ShipmentBy";
            cboShipmentby.ValueMember = "ShipmentBy";



            LoadPostCombo();
            LoadHeldCombo();
            LoadVerifyCombo();
            // cbo From 

            DataTable dtFrom = lookup.GetQuery("SELECT From_ FROM " + tableTVC_MFMOV + " group by From_ ORDER BY From_", ref sErr);
            DataRow dr4 = dtFrom.NewRow();
            dtFrom.Rows.Add(dr4);

            cboFrom.DataSource = dtFrom;
            cboFrom.DisplayMember = "From_";
            cboFrom.ValueMember = "From_";

            // cbo To 
            DataTable dtTo = lookup.GetQuery("SELECT To_ FROM " + tableTVC_MFMOV + " group by To_  ORDER BY To_ ", ref sErr);
            DataRow dr5 = dtTo.NewRow();
            dtTo.Rows.Add(dr5);

            cboTo.DataSource = dtTo;
            cboTo.DisplayMember = "To_";
            cboTo.ValueMember = "To_";

            BUS.CommonControl _impo = new CommonControl();
            string TableLookup = "TVC_LOOKUPPRV";
            if (PODInfo.Business_ID == "HV")
                TableLookup = "TVC_LOOKUPHVJ";

            // POSOContract            
            string query = " SELECT LTRIM(RTRIM(CODE)) AS Code, '' as  Lookup , NAME as Description FROM SSRFANV WHERE  (CATEGORY='T9') AND (PROHB_POST<>'Y') and SUN_DB='" + DTBSUN + "' ORDER BY CODE ";

            DataTable dtPCA = _impo.Getdata(_Connecstr, query, ref sErr);

            DataTable dt = lookup.GetQuery(" SELECT LTRIM(RTRIM(CODE)) AS Code AS CODE,Lookup, Description From " + TableLookup + " WHERE (TB='TVC_MFMOV') AND (TBField='POSOContract') AND (Status='' Or Status Is Null) ", ref sErr);
            dtPCA.Merge(dt);
            DataRow dr6 = dtPCA.NewRow();
            dr6["CODE"] = "";
            dr6["Lookup"] = "";
            dr6["Description"] = "";
            dtPCA.Rows.Add(dr6);
            GridLayout layoutPOSO = new GridLayout(MainForm.ServerPath
                + "Resources\\Layout\\", MainForm.ServerPath + "Documents\\Layout\\"
                + GetMainForm().PODInfo.USER_ID + "\\", "POSO");
            cboPO.DisplayMember = "Code";
            cboPO.ValueMember = "Code";
            //cboPO.DataSource = dtPCA;
            cboPO.MainForm = GetMainForm();
            cboPO.Layout = layoutPOSO;
            cboPO.DataSource = dtPCA;

            // Supplier
            DataTable dtSupplier = lookup.GetbycboStatus(" (Status='' Or Status Is Null) AND (TB='TVC_MFMOV') ORDER BY Code; ", "Supplier", ref sErr);
            DataRow dr7 = dtSupplier.NewRow();
            dtSupplier.Rows.Add(dr7);
            Supplier.DisplayMember = "Code";
            Supplier.ValueMember = "Code";
            Supplier.MainForm = GetMainForm();
            Supplier.Lookup = "Supplier";
            Supplier.DataSource = dtSupplier;
            //Supplier.DataSource = bisLookup;

            // WellCode

            string queryWellCode = " SELECT RTRIM(LTRIM(CODE)) as CODE, NAME as NAME, [LOOKUP] AS LOOKUP  FROM SSRFANV  WHERE (CATEGORY='T2') AND (PROHB_POST<>'Y')  AND (LOOKUP='WELL')  and SUN_DB='" + DTBSUN + "'  ORDER BY CODE ";
            DataTable dtwell = _impo.Getdata(_Connecstr, queryWellCode, ref sErr);
            DataRow dr9 = dtwell.NewRow();
            dr9["CODE"] = "";
            dr9["NAME"] = "";
            dr9["LOOKUP"] = "";
            dtwell.Rows.Add(dr9);

            cboWellCode.DisplayMember = "CODE";
            cboWellCode.ValueMember = "CODE";
            cboWellCode.MainForm = GetMainForm();
            cboWellCode.Lookup = "WellCode";

            cboWellCode.DataSource = dtwell;

            // Department
            DataTable dtDepartment = lookup.GetQuery(" SELECT Code, Description, Lookup from " + TableLookup + " WHERE (((TB)='TVC_RFITM' Or (TB)='TVC_MFMOV') AND ((TBField)='Department') AND ((Status)='' Or (Status) Is Null)) GROUP BY Code, Description, Lookup ORDER BY Code ", ref sErr);
            DataRow dr8 = dtDepartment.NewRow();
            dtDepartment.Rows.Add(dr8);

            cboDepartment.DataSource = dtDepartment;
            cboDepartment.DisplayMember = "Code";
            cboDepartment.ValueMember = "Code";




            //Delivery/Receipt Point

            DataTable dtDelivery = lookup.GetQuery(" SELECT DISTINCT Ltrim(Rtrim(DeliveryPoint)) as DeliveryPoint FROM " + tableTVC_MFMOV + " ORDER BY DeliveryPoint ", ref sErr);
            DataRow dr10 = dtDelivery.NewRow();
            dtDelivery.Rows.Add(dr10);

            cboDeliveryPoint.DataSource = dtDelivery;
            cboDeliveryPoint.DisplayMember = "DeliveryPoint";
            cboDeliveryPoint.ValueMember = "DeliveryPoint";

            // Item Code

            DataTable dtItem = rfitm.GetAll(ref sErr);
            DataRow drItem = dtItem.NewRow();
            dtItem.Rows.Add(drItem);
            DataView dvItem = dtItem.DefaultView;
            dvItem.Sort = "ItemCode ASC";
            //cboPosted.DataSource = 
            ItemCode.DisplayMember = "ItemCode";
            ItemCode.ValueMember = "ItemCode";
            ItemCode.MainForm = GetMainForm();
            ItemCode.Lookup = "ItemRecord";
            ItemCode.DataSource = dvItem.ToTable();


            DataTable dtStatus = lookup.GetbycboStatus("((Status)='' Or (Status) Is Null) AND ((TB)='TVC_MFMOV')", "Status", ref sErr);
            cboStatus.DataSource = dtStatus;
            cboStatus.DisplayMember = "Code";
            cboStatus.ValueMember = "Code";

            // Localtion

            DataTable dtLocaltion = lookup.GetbycboStatus(" ((Status)='' Or (Status) Is Null) AND ((TB)='TVC_MFMOV') ", "Location", ref sErr);
            DataRow drLocaltion = dtLocaltion.NewRow();
            dtLocaltion.Rows.Add(drLocaltion);

            cboLocation.DisplayMember = "Code";
            cboLocation.ValueMember = "Code";
            cboLocation.MainForm = GetMainForm();
            cboLocation.Lookup = "Localtion";
            cboLocation.DataSource = dtLocaltion;
            // cboBINnumber

            DataTable dtBinNo = lookup.GetbycboStatus(" ((Status)='' Or (Status) Is Null) AND ((TB)='TVC_MFMOV') ", "BINNo", ref sErr);
            DataRow drBinNo = dtBinNo.NewRow();
            dtBinNo.Rows.Add(drBinNo);
            cboBinNum.DataSource = dtBinNo;
            cboBinNum.DisplayMember = "Code";
            cboBinNum.ValueMember = "Code";

            //cboPartNo
            string TableTVC_MFMOV = "TVC_MFMOVPRV";
            if (PODInfo.Business_ID == "HV")
                TableTVC_MFMOV = "TVC_MFMOVHVJ";

            DataTable dtPartNo = lookup.GetQuery(" SELECT DISTINCT PartNo FROM " + TableTVC_MFMOV + " ORDER BY PartNo ", ref sErr);
            cboPartNo.DataSource = dtPartNo;
            cboPartNo.DisplayMember = "PartNo";
            cboPartNo.ValueMember = "PartNo";

            //cboAccountCode

            //BUS.IMPORT_SCHEMAControl _impo = new BUS.IMPORT_SCHEMAControl();
            string queryACCNT_CODE = " SELECT  LTrim(Rtrim(ACCNT_CODE)) as ACCNT_CODE, ACCNT_NAME, [LOOKUP] AS LOOKUP FROM SSRFACC WHERE SUN_DB ='" + DTBSUN + "' AND (SUSPEND<>'S' And SUSPEND<>'C') AND (ACCNT_CODE Like '13%' Or ACCNT_CODE Like '3%' Or ACCNT_CODE Like '8%') ORDER BY ACCNT_CODE ";
            //SELECT TRIM(ACCNT_CODE), ACCNT_NAME FROM SSRFACC WHERE (ACCNT_CODE Like '13%' Or ACCNT_CODE Like '3%' Or ACCNT_CODE Like '8%') AND (SUSPEND<>'S' And SUSPEND<>'C') ORDER BY ACCNT_CODE
            DataTable dtacc1 = _impo.Getdata(_Connecstr, queryACCNT_CODE, ref sErr);
            //DataTable dtacc2 = lookup.GetQuery(" SELECT TBField AS ACCNT_CODE, '' AS ACCNT_NAME FROM " + TableLookup + " GROUP BY TBField, TB HAVING (((TB)='LOOKUP_ACCNT'))  ", ref sErr);
            //dtacc1.Merge(dtacc2);
            DataRow dracc = dtacc1.NewRow();
            dracc["ACCNT_CODE"] = "";
            dracc["ACCNT_NAME"] = "";
            dracc["LOOKUP"] = "";
            //dracc["DisplayCBO"] = "";
            dtacc1.Rows.Add(dracc);
            cboAccountCode.DisplayMember = "ACCNT_CODE";
            cboAccountCode.ValueMember = "ACCNT_CODE";
            cboAccountCode.MainForm = GetMainForm();
            cboAccountCode.Lookup = "AccountCode";

            cboAccountCode.DataSource = dtacc1;


            //colSerialNo

            DataTable colSerialNo = lookup.GetQuery(" SELECT DISTINCT SerialNo FROM " + TableTVC_MFMOV + " ORDER BY SerialNo ", ref sErr);
            cboSerialNo.DataSource = colSerialNo;
            cboSerialNo.DisplayMember = "SerialNo";
            cboSerialNo.ValueMember = "SerialNo";

        }

        private void MovementType_SelectedValueChanged(object sender, EventArgs e)
        {
            if (_isvaluechange)
            {
                _isvaluechange = false;
                if (MovementType.SelectedItem is DataRowView)
                {
                    if (MovementType.Value.ToString() == "IGN0")
                    {
                        chkIntransit.Checked = true;
                    }
                    else
                        chkIntransit.Checked = false;
                    LoadAccountCode();
                    LoadDtWellCode();
                    lblMovementType.Text = ((DataRowView)MovementType.SelectedItem)["Description"].ToString();
                    _Prefix = ((DataRowView)MovementType.SelectedItem)["Prefix"].ToString();
                    _Mark = ((DataRowView)MovementType.SelectedItem)["Mark"].ToString();
                    _MovenmentAccount = ((DataRowView)MovementType.SelectedItem)["Account"].ToString();
                    //txtPeriod.Text = int.Parse(DateTime.Now.ToString("yyyy0MM")).ToString();
                    if (_processStatusLocal != "A")
                    {
                        if (_MovenmentAccount != "")
                        {
                            if (_MovenmentAccount.Substring(0, 1) == "_")
                                SetAccount(_MovenmentAccount, _Category);
                            else
                                cboAccountCode.Value = _MovenmentAccount;
                        }
                        else
                            cboAccountCode.Value = _MovenmentAccount;
                    }
                    if (_Mark == "-")
                    {
                        //numAmount.ReadOnly = true;
                        numAmount.Enabled = false;
                    }
                    else
                        numAmount.Enabled = true;
                }

                if (MovementType.Value.ToString() == "")
                    errProvider.SetError(MovementType, "Field Vendor Code is blank! Please check!");

                else errProvider.SetError(MovementType, "");

                if (_processStatusLocal != "A")
                {
                    txtReference.Text = GetRef(_Prefix);
                }
                DesignByType(MovementType.Value.ToString());
                DateTime dtime = dtpMovementDate.Value;
                txtPeriod.Text = int.Parse(dtime.ToString("yyyy0MM")).ToString();

                //MovementType.Focus();
                _isvaluechange = true;
            }
        }

        private string GetCode()
        {
            string strCode = "";

            string strYYMM = DateTime.Now.ToString("yyMM");
            BUS.TVC_LOOKUPControl lookup = new BUS.TVC_LOOKUPControl(PODInfo.Business_ID);
            string tableTVC_MFMOV = "TVC_MFMOVPRV";
            if (PODInfo.Business_ID == "HV")
            {
                tableTVC_MFMOV = "TVC_MFMOVHVJ";
            }
            string aNum = "";
            //select MAX(RIGHT([Code],4)) from TVC_MFMOVPRV where LEFT([Code],4) = '1104'
            DataTable dt = lookup.GetQuery("SELECT MAX(RIGHT([Code],4)) AS MaxNo FROM " + tableTVC_MFMOV + " WHERE LEFT([Code],4) = '" + strYYMM + "'", ref sErr);
            if (dt.Rows[0]["MaxNo"].ToString() == "")
                aNum = "0001";
            else
                aNum = (Convert.ToInt32(dt.Rows[0]["MaxNo"].ToString()) + 10001).ToString().Substring((Convert.ToInt32(dt.Rows[0]["MaxNo"].ToString()) + 10001).ToString().Length - 4, 4);

            strCode = strYYMM + "-" + aNum;

            return strCode;
        }

        private string GetPostCode(DataTable dt)
        {
            string strPostCode = "";

            string strYYMM = DateTime.Now.ToString("yyMM");           
            string aNum = "";
            if (dt.Rows[0]["MaxNo"].ToString() == "")
                aNum = "0001";
            else
                aNum = (Convert.ToInt32(dt.Rows[0]["MaxNo"].ToString()) + 10001).ToString().Substring((Convert.ToInt32(dt.Rows[0]["MaxNo"].ToString()) + 10001).ToString().Length - 4, 4);

            strPostCode = strYYMM + "-" + aNum;

            return strPostCode;
        }

        private string GetRef(string Prefix)
        {
            string strRef = "";
            if (_processStatus == "C" || _processStatus == "O")
            {
                if (Prefix == "")
                    Prefix = "ZZ";

                Prefix = Prefix + dtpMovementDate.Value.ToString("yyMM") + "-";
                BUS.TVC_LOOKUPControl lookup = new BUS.TVC_LOOKUPControl(PODInfo.Business_ID);
                string tableTVC_MFMOV = "TVC_MFMOVPRV";
                if (PODInfo.Business_ID == "HV")
                {
                    tableTVC_MFMOV = "TVC_MFMOVHVJ";
                }
                string aNum = "";
                DataTable dt = lookup.GetQuery("SELECT Max(SUBSTRING([Reference],8,2)) AS MaxNo FROM " + tableTVC_MFMOV + " WHERE LEFT([Reference],7)='" + Prefix + "' AND SUBSTRING(Reference,8,2) between '00'  and '99'", ref sErr);
                if (dt.Rows[0]["MaxNo"].ToString() == "")
                    aNum = "01";
                else
                    aNum = (Convert.ToInt32(dt.Rows[0]["MaxNo"].ToString()) + 1001).ToString().Substring((Convert.ToInt32(dt.Rows[0]["MaxNo"].ToString()) + 1001).ToString().Length - 2, 2);
                if (PODInfo.Business_ID == "HV")
                    strRef = Prefix + aNum + "V";
                else
                    strRef = Prefix + aNum + "L";
            }
            return strRef;
        }

        private void DesignByType(String MovenentType)
        {
            DTO.TVC_MVPInfo info = new DTO.TVC_MVPInfo();
            BUS.TVC_MVPControl ctr = new BUS.TVC_MVPControl(PODInfo.Business_ID);
            info = ctr.Get(MovenentType, ref sErr);
            LoadSetDefault(info);
            if (info.lblSupplier == "" || info.lblSupplier == null)
            {
                this.lblSupplier.Text = "Supplier";
            }
            else
                this.lblSupplier.Text = info.lblSupplier;

            this.cboShipmentby.Visible = Loadheader(info.headShipBy);
            this.lblShipmentby.Visible = Loadheader(info.headShipBy);

            this.dtpShipmentDate.Visible = Loadheader(info.headShipDate);
            this.lblShipmentDate.Visible = Loadheader(info.headShipDate);

            this.cboWellCode.Visible = Loadheader(info.headWell);
            this.lblWellCode.Visible = Loadheader(info.headWell);

            this.cboPO.Visible = Loadheader(info.headPO);
            this.lblPOSO.Visible = Loadheader(info.headPO);

            this.Supplier.Visible = Loadheader(info.headSupplier);
            this.lblSupplier.Visible = Loadheader(info.headSupplier);

            this.txtPino.Visible = Loadheader(info.headPI);
            this.lblPino.Visible = Loadheader(info.headPI);

            this.cboDepartment.Visible = Loadheader(info.headDepartment);
            this.lblDepartment.Visible = Loadheader(info.headDepartment);

            this.cboFrom.Visible = Loadheader(info.headFrom);
            lblFrom.Visible = Loadheader(info.headFrom);

            cboTo.Visible = Loadheader(info.headTo);
            lblTo.Visible = Loadheader(info.headTo);

            cboDeliveryPoint.Visible = Loadheader(info.headDelivery);
            lblDeliveryPoint.Visible = Loadheader(info.headDelivery);

            txtBLAWB.Visible = Loadheader(info.headBL);
            lblBL.Visible = Loadheader(info.headBL);            
        }

        private void LoadSetDefault(DTO.TVC_MVPInfo info)
        {
            if (_processStatusLocal == "")
            {
                Supplier.Value = info.Supplier;
                cboWellCode.Value = info.WellCode;
                if (info.Department != "")
                    cboDepartment.Text = info.Department;
                cboDeliveryPoint.Text = info.DeliveryPoint;                
                cboPO.Value = info.POSOContract;
                cboTo.SelectedValue = info.To_;
                
            }
        }

        private bool Loadheader(string p)
        {

            if (p == "" || p == "0")
            {
                return false;
            }
            else
                return true;
        }

        private void gridFilter1_GridFiterEvent(string strFilter, int year)
        {
            int intpage = dgvList.CurrentPage;
            string sErr = "";
            BUS.TVC_MFMOVControl MMQCtr = new BUS.TVC_MFMOVControl(PODInfo.Business_ID);
            DataTable dtb = null;
            _strFilter = strFilter;
            _gridFilter = strFilter;
            dtb = MMQCtr.GetbyFilter(strFilter, ref sErr);
            bisMME.DataSource = dtb;
            double maxrow = Convert.ToDouble(dtb.Rows.Count) / Convert.ToDouble(dgvList.ItemsPerPage);
            if (maxrow >= intpage - 0.9)
            {
                dgvList.CurrentPage = intpage;
            }
        }



        private void bgTextView()
        {
            _btnPost = false;
            foreach (Control x in pnDetail.Controls)
            {
                if (x is TextBox || x is ComboBox || x is TVC.Modules.CustomControl.MultiColumnCombo || x is NumericUpDown || x is DatePicker || x is ComboBox || x is CustomControl.LookupBox || x is CustomControl.DateTimeCustom)
                {
                    if (x.Name != "txtPeriod")
                    {
                        x.Enabled = false;
                        x.ForeColor = System.Drawing.Color.Black;
                        x.BackColor = System.Drawing.Color.White;
                    }
                }

            }
        }

        private void SetData(DTO.TVC_MFMOVInfo info)
        {
            //_isvaluechange = false;
            if (_status == "Hold" || info.PostCode == "Z")
                lblHoldStatus.Text = "HELD";
            else if (_status == "Posted" || info.PostCode != "Z")
            {
                lblHoldStatus.Text = "POSTED   " + info.PostCode;

            }
            else
                lblHoldStatus.Text = "";
            strCode = info.Code;
            _Reference = info.Reference;
            // _PostCode = info.PostCode;
            //_isvaluechange = true;
            MovementType.Value = info.Type;
            ItemCode.Value = info.ItemCode;
            //_isvaluechange = false;
            txtPeriod.Text = info.Period.ToString();
            cboTo.Text = info.To_;
            cboFrom.Text = info.From_;
            txtPino.Text = info.PINo.ToString();
            cboPO.Value = info.POSOContract;
            Supplier.Value = info.Supplier;
            cboWellCode.Value = info.WellCode;
            cboDepartment.SelectedValue = info.Department;
            txtRemark.Text = info.Remark;
            cboDeliveryPoint.Text = info.DeliveryPoint;
            dtpMovementDate.Value = info.TransDate;
            dtpShipmentDate.Value = info.ShipmentDate;
            txtReference.Text = info.Reference;
            txtBLAWB.Text = info.BLAWBNo;
            cboShipmentby.Text = info.ShipmentBy;
            lblQty.Value = info.Quantity;
            lblValue.Value = decimal.Parse(info.Amount.ToString());
            cboPartNo.Text = info.PartNo;
            cboSerialNo.Text = info.SerialNo;
            cboStatus.SelectedValue = info.Status;
            cboLocation.Value = info.Location;
            cboBinNum.SelectedValue = info.BINNo;
            cboAccountCode.Value = info.Account;
            //cboAccountCode.Text = info.Account;
            numAmount.Value = Math.Abs((decimal)info.Amount);
            numQuantity.Value = Math.Abs(info.Quantity);
            BalRef(info.Reference);
            _infoDetail = info;
            if (info.OtherValue1 != 0 || info.OtherValue2 != 0)
            {
                btnDetail.Enabled = true;
            }
            else
                btnDetail.Enabled = false;
            //Doclink.Initialization(GetMainForm().PODInfo.Business_ID.ToString().Trim(), _strType, info.Reference, GetMainForm());
            Doclink.reLoad(info.Reference);
            if (info.Intransit != null)
                chkIntransit.Checked = info.Intransit == "Y" ? true : false;
            _Verified = info.Verified;
            ToolTip oPn = new ToolTip();
            oPn.SetToolTip(this.btFartno, info.PartNo);
            _isvaluechange = false;
            cboHeld.Text = "";
            cboVerify.Text = "";
            cboPosted.Text = "";
            _isvaluechange = true;
        }
        private void BalRef(string aRef)
        {
            BUS.TVC_LOOKUPControl lookup = new BUS.TVC_LOOKUPControl(PODInfo.Business_ID);
            string tableTVC_MFMOV = "TVC_MFMOVPRV";
            if (PODInfo.Business_ID == "HV")
            {
                tableTVC_MFMOV = "TVC_MFMOVHVJ";
            }
            string aNum = "";
            DataTable dt = lookup.GetQuery("SELECT Sum(Quantity) AS RefQty, Sum(Amount) AS RefAmt FROM " + tableTVC_MFMOV + " WHERE (Reference='" + aRef + "') ", ref sErr);
            if (dt.Rows.Count > 0 && dt.Rows[0]["RefQty"].ToString() != "")
            {
                lblQty.Value = Math.Abs(decimal.Parse(dt.Rows[0]["RefQty"].ToString()));
                if (dt.Rows[0]["RefAmt"].ToString().Length > 9)
                    lblValue.Value = Math.Abs(decimal.Parse(dt.Rows[0]["RefAmt"].ToString().Substring(0, 9)));
                else
                    lblValue.Value = Math.Abs(decimal.Parse(dt.Rows[0]["RefAmt"].ToString()));

            }
        }
        private void ItemCode_SelectedValueChanged(object sender, EventArgs e)
        {
            if (_isvaluechange)
            {
                _isvaluechange = false;
                if (ItemCode.SelectedItem is DataRowView)
                {
                    if (ItemCode.Text != "")
                    {
                        string tableTVC_MFMOV = "TVC_MFMOVPRV";
                        if (PODInfo.Business_ID == "HV")
                        {
                            tableTVC_MFMOV = "TVC_MFMOVHVJ";
                        }
                        BUS.TVC_LOOKUPControl lookup = new BUS.TVC_LOOKUPControl(PODInfo.Business_ID);
                        DataTable dtPartNo = lookup.GetQuery(" SELECT DISTINCT PartNo FROM " + tableTVC_MFMOV + " where ItemCode = '" + ItemCode.Value.ToString() + "'  ORDER BY PartNo ", ref sErr);
                        cboPartNo.DataSource = dtPartNo;
                        cboPartNo.DisplayMember = "PartNo";
                        cboPartNo.ValueMember = "PartNo";

                        //  numAmount.Value = 0;

                        //colSerialNo
                        DataTable colSerialNo = lookup.GetQuery(" SELECT DISTINCT SerialNo FROM " + tableTVC_MFMOV + " where ItemCode = '" + ItemCode.Value.ToString() + "'    ORDER BY SerialNo ", ref sErr);
                        cboSerialNo.DataSource = colSerialNo;
                        cboSerialNo.DisplayMember = "SerialNo";
                        cboSerialNo.ValueMember = "SerialNo";
                        lblItemCode.Text = ((DataRowView)ItemCode.SelectedItem)["Description"].ToString();
                        ToolTip oTP = new ToolTip();
                        oTP.SetToolTip(this.btDesc, lblItemCode.Text);
                        cboPartNo.Text = ((DataRowView)ItemCode.SelectedItem)["ANAL_I4"].ToString();
                        ToolTip oTP1 = new ToolTip();
                        oTP1.SetToolTip(this.btFartno, cboPartNo.Text);
                        LoadValue(ItemCode.Value.ToString());
                        _Category = ((DataRowView)ItemCode.SelectedItem)["Category"].ToString();
                        if (_MovenmentAccount != "" && _MovenmentAccount != null)
                        {
                            if (_MovenmentAccount.Substring(0, 1) == "_")
                                SetAccount(_MovenmentAccount, _Category);
                            else
                                cboAccountCode.Text = _MovenmentAccount;
                        }
                        else
                            cboAccountCode.Text = _MovenmentAccount;
                        _isvaluechange = true;
                        cboDepartment.SelectedValue = ((DataRowView)ItemCode.SelectedItem)["Department"].ToString();
                        _isvaluechange = false;

                    }
                }
                _isvaluechange = true;
            }
        }

        private void SetAccount(string _MovenmentAccount, string Category)
        {
            BUS.TVC_LOOKUPControl ctr = new TVC_LOOKUPControl(PODInfo.Business_ID);

            DataTable dt = ctr.GetDescription("LOOKUP_ACCNT", _MovenmentAccount, Category, ref sErr);
            if (dt.Rows.Count > 0)
            {
                cboAccountCode.Text = dt.Rows[0]["Description"].ToString();
            }
        }
        private void LoadValue(string ItemCode)
        {
            if (ItemCode != "System.Data.DataRowView" && ItemCode != "")
            {
                BUS.TVC_MFMOVControl ctr = new TVC_MFMOVControl(PODInfo.Business_ID);
                DTO.TVC_MFMOVInfo info = new DTO.TVC_MFMOVInfo();
                info = ctr.GetbyItemCode(ItemCode, ref sErr);
                if (cboPartNo.Text != null && cboPartNo.Text == "")
                {
                    cboPartNo.Text = info.PartNo;
                }
                cboSerialNo.SelectedValue = info.SerialNo;
                cboAccountCode.Text = info.Account;
               
                if (_Mark == "+")
                    cboSerialNo.SelectedValue = "";
                dtSumQty = ctr.GetItemSumByRef(null, ref sErr);
                if (ItemCode != "" && info.Location != "")
                {
                    object sum = dtSumQty.Compute("SUM(Quantity)", string.Format("ItemCode = '{0}' AND Location ='{1}'", ItemCode, info.Location));
                    if (sum != null)
                        lblQtyLocation.Text = sum.ToString();
                    else lblQtyLocation.Text = "0";
                }
                //cboPartNo.Focus();
            }
        }
        private void dtpMovementDate_ValueChanged(object sender, EventArgs e)
        {
            if (_isvaluechange == true)
            {
                _isvaluechange = false;
                DateTime dtime = dtpMovementDate.Value;
                txtReference.Text = GetRef(_Prefix);
                txtPeriod.Text = int.Parse(dtime.ToString("yyyy0MM")).ToString();
                _isvaluechange = true;
            }
        }

        private void cboHeld_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (_isvaluechange)
            {
                _isvaluechange = false;
                if (cboHeld.Text != "System.Data.DataRowView" && cboHeld.Text != "")
                {
                    //Doclink.Initialization(_DB, _strType, cboHeld.Text, GetMainForm());
                    _status = "Hold";
                    cboPosted.Text = "";
                    cboVerify.Text = "";
                    refreshForm("");

                    _strFilter = " Reference = '" + cboHeld.SelectedValue.ToString() + "'  ";
                    _strcboHeld = cboHeld.SelectedValue.ToString();
                    _strcboPosted = "";
                    LoadGrid(cboHeld.SelectedValue.ToString());
                    dgvList.ReadOnly = true;
                    dgvList.AllowUserToAddRows = false;
                    if (dgvList.CurrentCell != null)
                    {
                        DTO.TVC_MFMOVInfo info = new DTO.TVC_MFMOVInfo((DataRowView)dgvList.CurrentRow.DataBoundItem);
                        SetData(info);
                        bgTextView();
                    }
                    //skip();
                    SetupToolBar("V");
                }
                _isvaluechange = true;
            }
        }

        private void LoadGrid(string Reference)
        {
            int intpage = dgvList.CurrentPage;
            BUS.TVC_MFMOVControl ctrmov = new BUS.TVC_MFMOVControl(PODInfo.Business_ID);
            bisMME.DataSource = ctrmov.GetbyReference(Reference, null, ref sErr);
            DataTable dtb = (DataTable)bisMME.DataSource;
            double maxrow = Convert.ToDouble(dtb.Rows.Count) / Convert.ToDouble(dgvList.ItemsPerPage);
            if (maxrow >= intpage - 0.9)
            {
                dgvList.CurrentPage = intpage;
            }
        }
        private void cboPosted_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (_isvaluechange)
            {
                _isvaluechange = false;
                if (cboPosted.Text != "System.Data.DataRowView" && cboPosted.Text != "")
                {
                    //Doclink.Initialization(_DB, _strType, cboPosted.Text, GetMainForm());
                    _status = "Posted";
                    cboHeld.Text = "";
                    cboVerify.Text = "";
                    refreshForm("");
                    _strFilter = " Reference = '" + cboPosted.SelectedValue.ToString() + "'  ";
                    _strcboHeld = "";
                    _strcboPosted = cboPosted.SelectedValue.ToString();
                    LoadGrid(cboPosted.SelectedValue.ToString());
                    dgvList.ReadOnly = true;
                    dgvList.AllowUserToAddRows = false;
                    if (dgvList.CurrentCell != null)
                    {
                        DTO.TVC_MFMOVInfo info = new DTO.TVC_MFMOVInfo((DataRowView)dgvList.CurrentRow.DataBoundItem);
                        SetData(info);
                        bgTextView();
                    }
                    SetupToolBar("V");
                }
                _isvaluechange = true;
            }
        }

        private void cboPartNo_SelectedValueChanged(object sender, EventArgs e)
        {
            if (_isvaluechange)
            {
                _isvaluechange = false;
                if (cboPartNo.Text != "System.Data.DataRowView" && cboPartNo.Text != "")
                {
                    string sErr = "";
                    BUS.TVC_LOOKUPControl lookup = new BUS.TVC_LOOKUPControl(PODInfo.Business_ID);

                    string tableTVC_MFMOV = "TVC_MFMOVPRV";
                    if (PODInfo.Business_ID == "HV")
                    {
                        tableTVC_MFMOV = "TVC_MFMOVHVJ";
                    }
                    //colSerialNo

                    DataTable colSerialNo = lookup.GetQuery(" SELECT DISTINCT SerialNo FROM " + tableTVC_MFMOV + " where ItemCode = '" + ItemCode.Value.ToString() + "' and PartNo = '" + cboPartNo.SelectedValue.ToString() + "'   ORDER BY SerialNo ", ref sErr);
                    cboSerialNo.DataSource = colSerialNo;
                    cboSerialNo.DisplayMember = "SerialNo";
                    cboSerialNo.ValueMember = "SerialNo";
                }
                _isvaluechange = true;
            }
        }

        private void cboLocation_SelectedValueChanged(object sender, EventArgs e)
        {
            if (_isvaluechange)
            {
                _isvaluechange = false;
                if (ItemCode.Text != "" && cboLocation.Text != "" && cboLocation.Text != "System.Data.DataRowView")
                {
                    BUS.TVC_MFMOVControl ctr = new BUS.TVC_MFMOVControl(PODInfo.Business_ID);

                    dtSumQty = ctr.GetItemSumByRef(null, ref sErr);

                    object sum = dtSumQty.Compute("SUM(Quantity)", string.Format("ItemCode = '{0}' AND Location ='{1}'", ItemCode.Text, cboLocation.Text));
                    if (sum != null)
                        lblQtyLocation.Text = sum.ToString();
                    else lblQtyLocation.Text = "0";

                }
                _isvaluechange = true;
            }
        }

        private void cboPO_Leave(object sender, EventArgs e)
        {
            if (cboPO.Text != null)
            {
                if (cboPO.Text.Trim() != "")
                {
                    if (cboPO.Value.ToString().Trim() == "")
                    {
                        //cboWellCode.Value = "";
                        cboPO.Focus();
                        MessageBox.Show(" Please select from the list ", false);
                    }
                }
            }
        }

        private void Supplier_Leave(object sender, EventArgs e)
        {
            if (Supplier.Text != null)
            {
                if (Supplier.Text.Trim() != "")
                {
                    if (Supplier.Value.ToString().Trim() == "")
                    {
                        //cboWellCode.Value = "";
                        Supplier.Focus();
                        MessageBox.Show(" Please select from the list ", false);
                    }
                }
            }

        }

        private void cboDepartment_Leave(object sender, EventArgs e)
        {
            if (cboDepartment.Text != null)
            {
                if (cboDepartment.Text.Trim() != "")
                {
                    if (cboDepartment.SelectedValue != null)
                    {
                        if (cboDepartment.SelectedValue.ToString().Trim() == "")
                        {
                            //cboWellCode.Value = "";
                            cboDepartment.Focus();
                            MessageBox.Show(" Please select from the list ", false);
                        }
                    }
                }
            }

        }

        private void cboWellCode_Leave(object sender, EventArgs e)
        {
            if (cboWellCode.Text != null)
            {
                if (cboWellCode.Text.Trim() != "")
                {
                    if (cboWellCode.Value.ToString().Trim() == "")
                    {
                        //cboWellCode.Value = "";
                        cboWellCode.Focus();
                        MessageBox.Show(" Please select from the list ", false);
                    }
                }
            }
        }

        private void ItemCode_Leave(object sender, EventArgs e)
        {
            if (_isvaluechange)
            {
                _isvaluechange = false;
                if (ItemCode.Text != null)
                {
                    if (ItemCode.Text.Trim() != "")
                    {
                        if (ItemCode.Value.ToString().Trim() == "")
                        {
                            //cboWellCode.Value = "";
                            ItemCode.Focus();
                            MessageBox.Show(" Please select from the list ", false);
                        }
                    }
                }
                _isvaluechange = true;
            }
        }

        private void Supplier_SelectedValueChanged(object sender, EventArgs e)
        {
            if (_isvaluechange)
            {
                _isvaluechange = false;
                if (Supplier.DataSource != null && Supplier.SelectedItem != null)
                {

                    cboDeliveryPoint.SelectedValue = ((DataRowView)Supplier.SelectedItem)["Description"].ToString().Trim();
                    cboDeliveryPoint.Text = ((DataRowView)Supplier.SelectedItem)["Description"].ToString().Trim();
                }
                _isvaluechange = true;
            }
        }

        private void MovementType_Leave(object sender, EventArgs e)
        {
            if (MovementType.Text != null)
            {
                if (MovementType.Text.Trim() != "")
                {
                    if (MovementType.Value.ToString().Trim() == "")
                    {
                        MovementType.Focus();
                        MessageBox.Show(" Please select from the list ", false);
                    }
                }
            }
        }

        private void LoadDtWellCode()
        {
            if (_isvaluechange)
            {
                _isvaluechange = false;
                string strLookup = "";
                if (MovementType.SelectedItem is DataRowView)
                {
                    strLookup = ((DataRowView)MovementType.SelectedItem)["Lookup"].ToString();
                }
                String strDeparment = "";
                if (cboDepartment.SelectedValue != null)
                    strDeparment = cboDepartment.SelectedValue.ToString().Trim();
                BUS.CommonControl _impo = new CommonControl();
                string DTBSUN = Properties.Settings.Default.SUNHL;
                if (PODInfo.Business_ID == "HV")
                {
                    DTBSUN = Properties.Settings.Default.SUNHV;
                }
                if (strDeparment == "PRD" && (MovementType.Value.ToString() == "IGN0" || strLookup == "RMN"))
                {
                    // WellCode
                    string strWellCode = cboWellCode.Value.ToString();
                    string queryWellCode = " SELECT RTRIM(LTRIM(CODE)) as CODE, NAME , [LOOKUP] AS LOOKUP FROM SSRFANV WHERE (CATEGORY='T2') AND (PROHB_POST<>'Y')  AND (CODE Like 'PO%')  AND SUN_DB='" + DTBSUN + "'ORDER BY CODE ";
                    //SELECT LTRIM(RTRIM(CODE)) as CODE, NAME as NAME FROM SSRFANV WHERE (CATEGORY='T2') AND (PROHB_POST<>'Y')  AND (LOOKUP='WELL')  and SUN_DB='" + DTBSUN + "'  ORDER BY CODE ";
                    DataTable dtwell = _impo.Getdata(_Connecstr, queryWellCode, ref sErr);
                    DataRow dr9 = dtwell.NewRow();
                    dr9["CODE"] = "";
                    dr9["NAME"] = "";
                    dr9["LOOKUP"] = "";
                    dtwell.Rows.Add(dr9);
                    //cboWellCode.DisplayMember = "CODE";
                    //cboWellCode.ValueMember = "CODE";
                    cboWellCode.MainForm = GetMainForm();
                    cboWellCode.Lookup = "WellCode";
                    cboWellCode.DataSource = dtwell;
                    cboWellCode.Value = strWellCode;

                }
                else if (strDeparment == "OPS" && MovementType.Value.ToString() == "IGN0")
                {
                    string strWellCode = cboWellCode.Value.ToString();
                    string queryWellCode = " SELECT RTRIM(LTRIM(CODE)) as CODE, NAME as NAME, [LOOKUP] AS LOOKUP  FROM SSRFANV  WHERE (CATEGORY='T2') AND (PROHB_POST<>'Y')  AND (LOOKUP='WELL')  and SUN_DB='" + DTBSUN + "'  ORDER BY CODE ";
                    DataTable dtwell = _impo.Getdata(_Connecstr, queryWellCode, ref sErr);
                    DataRow dr9 = dtwell.NewRow();
                    dr9["CODE"] = "";
                    dr9["NAME"] = "";
                    dr9["LOOKUP"] = "";
                    dtwell.Rows.Add(dr9);
                    //cboWellCode.DisplayMember = "CODE";
                    //cboWellCode.ValueMember = "CODE";
                    //cboWellCode.MainForm = GetMainForm();
                    //cboWellCode.Lookup = "WellCode";
                    cboWellCode.DataSource = dtwell;
                    cboWellCode.Value = strWellCode;
                }
                else
                {
                    string strWellCode = cboWellCode.Value.ToString();
                    string queryWellCode = " SELECT RTRIM(LTRIM(CODE)) as CODE, NAME as NAME, [LOOKUP] AS LOOKUP  FROM SSRFANV  WHERE (CATEGORY='T2') AND (PROHB_POST<>'Y')  AND (LOOKUP='WELL')  and SUN_DB='" + DTBSUN + "'  ORDER BY CODE ";
                    DataTable dtwell = _impo.Getdata(_Connecstr, queryWellCode, ref sErr);
                    DataRow dr9 = dtwell.NewRow();
                    dr9["CODE"] = "";
                    dr9["NAME"] = "";
                    dr9["LOOKUP"] = "";
                    dtwell.Rows.Add(dr9);
                    //cboWellCode.DisplayMember = "CODE";
                    //cboWellCode.ValueMember = "CODE";
                    //cboWellCode.MainForm = GetMainForm();
                    //cboWellCode.Lookup = "WellCode";
                    cboWellCode.DataSource = dtwell;
                    cboWellCode.Value = strWellCode;
                }


                _isvaluechange = true;
            }
        }

        private void cboDepartment_SelectedValueChanged(object sender, EventArgs e)
        {
            //if (_isvaluechange)
            //{
            //    _isvaluechange = false;
            if (cboDepartment.SelectedValue != null)
            {
                LoadDtWellCode();
                LoadAccountCode();
            }
            //    _isvaluechange = true;
            //}
        }

        private void LoadAccountCode()
        {
            if (_isvaluechange)
            {
                _isvaluechange = false;
                string strLookup = "";
                if (MovementType.SelectedItem is DataRowView)
                {
                    strLookup = ((DataRowView)MovementType.SelectedItem)["Lookup"].ToString();
                }
                String strDeparment = "";
                if (cboDepartment.SelectedValue != null)
                    strDeparment = cboDepartment.SelectedValue.ToString().Trim();
                BUS.CommonControl _impo = new CommonControl();
                string DTBSUN = Properties.Settings.Default.SUNHL;
                if (PODInfo.Business_ID == "HV")
                {
                    DTBSUN = Properties.Settings.Default.SUNHV;
                }
                if (strDeparment == "OPS" && (MovementType.Value.ToString() == "IGN0" || strLookup == "RMN"))
                {

                    //cboAccountCode
                    string acc = cboAccountCode.Value.ToString();
                    string queryACCNT_CODE = " SELECT  LTrim(Rtrim(ACCNT_CODE)) as ACCNT_CODE, ACCNT_NAME, [LOOKUP] AS LOOKUP FROM SSRFACC WHERE SUN_DB ='" + DTBSUN + "' AND (SUSPEND<>'S' And SUSPEND<>'C') AND (ACCNT_CODE Like '82%' OR ACCNT_CODE Like '83%') ORDER BY ACCNT_CODE ";
                    DataTable dtacc1 = _impo.Getdata(_Connecstr, queryACCNT_CODE, ref sErr);
                    DataRow dracc = dtacc1.NewRow();
                    dracc["ACCNT_CODE"] = "";
                    dracc["ACCNT_NAME"] = "";
                    dracc["LOOKUP"] = "";
                    //dracc["DisplayCBO"] = "";
                    dtacc1.Rows.Add(dracc);
                    cboAccountCode.DisplayMember = "ACCNT_CODE";
                    cboAccountCode.ValueMember = "ACCNT_CODE";
                    cboAccountCode.MainForm = GetMainForm();
                    cboAccountCode.Lookup = "AccountCode";

                    cboAccountCode.DataSource = dtacc1;
                    cboAccountCode.Value = acc;
                }
                else if (strDeparment == "PRD" && MovementType.Value.ToString() == "IGN0")
                {
                    string acc = cboAccountCode.Value.ToString();
                    string queryACCNT_CODE = " SELECT  LTrim(Rtrim(ACCNT_CODE)) as ACCNT_CODE, ACCNT_NAME, [LOOKUP] AS LOOKUP FROM SSRFACC WHERE SUN_DB ='" + DTBSUN + "' AND (SUSPEND<>'S' And SUSPEND<>'C') AND (ACCNT_CODE Like '85%') ORDER BY ACCNT_CODE ";
                    DataTable dtacc1 = _impo.Getdata(_Connecstr, queryACCNT_CODE, ref sErr);
                    DataRow dracc = dtacc1.NewRow();
                    dracc["ACCNT_CODE"] = "";
                    dracc["ACCNT_NAME"] = "";
                    dracc["LOOKUP"] = "";
                    //dracc["DisplayCBO"] = "";
                    dtacc1.Rows.Add(dracc);
                    cboAccountCode.DisplayMember = "ACCNT_CODE";
                    cboAccountCode.ValueMember = "ACCNT_CODE";
                    cboAccountCode.MainForm = GetMainForm();
                    cboAccountCode.Lookup = "AccountCode";
                    cboAccountCode.DataSource = dtacc1;
                    cboAccountCode.Value = acc;
                }
                else
                {
                    string acc = cboAccountCode.Value.ToString();
                    string queryACCNT_CODE = " SELECT  LTrim(Rtrim(ACCNT_CODE)) as ACCNT_CODE, ACCNT_NAME, [LOOKUP] AS LOOKUP FROM SSRFACC WHERE SUN_DB ='" + DTBSUN + "' AND (SUSPEND<>'S' And SUSPEND<>'C') AND (ACCNT_CODE Like '13%' Or ACCNT_CODE Like '3%' Or ACCNT_CODE Like '8%') ORDER BY ACCNT_CODE ";
                    DataTable dtacc1 = _impo.Getdata(_Connecstr, queryACCNT_CODE, ref sErr);
                    DataRow dracc = dtacc1.NewRow();
                    dracc["ACCNT_CODE"] = "";
                    dracc["ACCNT_NAME"] = "";
                    dracc["LOOKUP"] = "";
                    //dracc["DisplayCBO"] = "";
                    dtacc1.Rows.Add(dracc);
                    cboAccountCode.DisplayMember = "ACCNT_CODE";
                    cboAccountCode.ValueMember = "ACCNT_CODE";
                    cboAccountCode.MainForm = GetMainForm();
                    cboAccountCode.Lookup = "AccountCode";
                    cboAccountCode.DataSource = dtacc1;
                    cboAccountCode.Value = acc;
                }
                _isvaluechange = true;
            }
        }

        private void cboLocation_Leave(object sender, EventArgs e)
        {
            if (cboLocation.Text != null)
            {
                if (cboLocation.Text.Trim() != "")
                {
                    if (cboLocation.Value.ToString().Trim() == "")
                    {
                        cboLocation.Focus();
                        MessageBox.Show(" Please select from the list ", false);
                    }
                }
            }
        }

        public DataRow SetDataRow(DataRow dr, DTO.TVC_MFMOVInfo info)
        {
            dr["Code"] = info.Code;
            dr["PostCode"] = info.PostCode;
            dr["Type"] = info.Type;
            dr["Description"] = info.Description;
            dr["Period"] = info.Period;
            dr["TransDate"] = info.TransDate;
            dr["Reference"] = info.Reference;
            dr["ShipmentDate"] = info.ShipmentDate;
            dr["ShipmentBy"] = info.ShipmentBy;
            dr["BLAWBNo"] = info.BLAWBNo;
            dr["DeliveryPoint"] = info.DeliveryPoint;
            dr["Remark"] = info.Remark;
            dr["From_"] = info.From_;
            dr["To_"] = info.To_;
            dr["Supplier"] = info.Supplier;
            dr["WellCode"] = info.WellCode;
            dr["Department"] = info.Department;
            dr["PINo"] = info.PINo;
            dr["ItemCode"] = info.ItemCode;
            dr["PartNo"] = info.PartNo;
            dr["SerialNo"] = info.SerialNo;
            dr["Status"] = info.Status;
            dr["Location"] = info.Location;
            dr["Quantity"] = info.Quantity;
            dr["Amount"] = info.Amount;
            dr["POSOContract"] = info.POSOContract;
            dr["Account"] = info.Account;
            dr["isLink"] = info.isLink;
            dr["Hold"] = info.Hold;
            dr["Average"] = info.Average;
            dr["BINNo"] = info.BINNo;
            dr["ANAL_M0"] = info.ANAL_M0;
            dr["ANAL_M1"] = info.ANAL_M1;
            dr["ANAL_M2"] = info.ANAL_M2;
            dr["ANAL_M3"] = info.ANAL_M3;
            dr["ANAL_M4"] = info.ANAL_M4;
            dr["ANAL_M5"] = info.ANAL_M5;
            dr["SUNStatus"] = info.SUNStatus;
            dr["PostBy"] = info.PostBy;
            dr["PostDate"] = info.PostDate;
            dr["CreatedBy"] = info.CreatedBy;
            dr["ModifiedBy"] = info.ModifiedBy;
            dr["CreatedDate"] = info.CreatedDate;
            dr["ModifiedDate"] = info.ModifiedDate;
            dr["POValue"] = info.POValue;
            dr["OtherValue1"] = info.OtherValue1;
            dr["OtherValue2"] = info.OtherValue2;
            dr["OtherValue3"] = info.OtherValue3;
            dr["Intransit"] = info.Intransit;
            return dr;
        }

        private void cboWellCode_SelectedValueChanged(object sender, EventArgs e)
        {
            if (_isvaluechange)
            {
                _isvaluechange = false;
                if (cboWellCode.SelectedItem != null)
                    cboDeliveryPoint.Text = ((DataRowView)cboWellCode.SelectedItem)["NAME"].ToString().Trim();
                _isvaluechange = true;
            }
        }

        private void btnDetail_Click(object sender, EventArgs e)
        {
            sErr = "";
            if (_infoDetail != null)
            {
                if (_infoDetail.ANAL_M0 == "Y")
                {

                    //DataTable dtResoure = dgvDetail.DataSource as DataTable;
                    //DataRowView currentDataRowView = (DataRowView)dgvDetail.CurrentRow.DataBoundItem;
                    //DataRow row = currentDataRowView.Row;
                    AmountDetail spl = new AmountDetail();
                    spl.infoMOV = _infoDetail;
                    spl.ShowDialog();
                }
            }
        }

        private void lblItemCode_DoubleClick(object sender, EventArgs e)
        {
            Forms.frmPopupText frm = new Forms.frmPopupText();
            frm.Value = lblItemCode.Text;
            frm.EnableBox = lblItemCode.Enabled;
            frm.Text = lblItemCode.Text;
            frm.FormClosed += (form, args) =>
            {
                if (((Forms.frmPopupText)form).DialogResult == DialogResult.OK)
                {
                    lblItemCode.Text = frm.Value;
                }
                lblItemCode.Focus();
            };
            frm.ShowDialog();
        }

        private void btDesc_Click(object sender, EventArgs e)
        {
            Forms.frmPopupText frm = new Forms.frmPopupText();
            frm.Value = lblItemCode.Text;
            frm.EnableBox = lblItemCode.Enabled;
            frm.Text = "Item Description";
            frm.FormClosed += (form, args) =>
            {
                if (((Forms.frmPopupText)form).DialogResult == DialogResult.OK)
                {
                    lblItemCode.Text = frm.Value;
                }
                lblItemCode.Focus();
            };
            frm.ShowDialog();

        }



        private void cboVerify_SelectedValueChanged(object sender, EventArgs e)
        {
            if (_isvaluechange)
            {
                _isvaluechange = false;
                if (cboVerify.Text != "System.Data.DataRowView" && cboVerify.Text != "")
                {
                    cboHeld.Text = "";
                    cboPosted.Text = "";
                    refreshForm("");
                    _strFilter = " Reference = '" + cboVerify.SelectedValue.ToString() + "'  ";
                    _strcboHeld = "";
                    _strcboVerify = cboVerify.SelectedValue.ToString();
                    LoadGrid(cboVerify.SelectedValue.ToString());
                    dgvList.ReadOnly = true;
                    dgvList.AllowUserToAddRows = false;
                    if (dgvList.CurrentCell != null)
                    {
                        DTO.TVC_MFMOVInfo info = new DTO.TVC_MFMOVInfo((DataRowView)dgvList.CurrentRow.DataBoundItem);
                        SetData(info);
                        bgTextView();
                    }
                    SetupToolBar("V");
                }
                _isvaluechange = true;
            }
        }

        private void btFartno_Click(object sender, EventArgs e)
        {
            Forms.frmPopupText frm = new Forms.frmPopupText();
            frm.Value = cboPartNo.Text;
            frm.EnableBox = cboPartNo.Enabled;
            frm.Text = "Part No";
            frm.FormClosed += (form, args) =>
            {
                if (((Forms.frmPopupText)form).DialogResult == DialogResult.OK)
                {
                    cboPartNo.Text = frm.Value;
                }
                cboPartNo.Focus();
            };
            frm.ShowDialog();
        }
    }
}